DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  • Faster Releases With DevOps: Java Microservices and Angular UI in CI/CD
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Legacy Code Refactoring: Tips, Steps, and Best Practices

Trending

  • Advanced Error Handling and Retry Patterns in Enterprise REST Integrations
  • Observability for Agents and Workflows: Tracing Prompts, Tool Calls, and Business Outcomes End-to-End
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Identity in Action
  1. DZone
  2. Coding
  3. Frameworks
  4. Angular JS: Use an Angular Websocket Client with a Java Websocket Endpoint

Angular JS: Use an Angular Websocket Client with a Java Websocket Endpoint

In this tip you can see how to use the Angular Websocket module for connecting client applications to servers.

By 
Anghel Leonard user avatar
Anghel Leonard
DZone Core CORE ·
Jan. 16, 15 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
40.4K Views

Join the DZone community and get the full member experience.

Join For Free

In this tip you can see how to use the Angular Websocket module for connecting client applications to servers. For this case, we have a Java endpoint, as below:

package com.mycompany.angularws;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/atpendpoint")
public class ATPWSEndpoint {

    private static final Logger LOG = Logger.getLogger(ATPWSEndpoint.class.getName());
    private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());

    @OnMessage
    public String onMessage(String message) {
        if (message != null) {
            if (message.equals("HELLO SERVER")) {
                return "{\"hello\": \"Hello, if you need the ATP list just press the button ...\"}";
            } else if (message.equals("ATP SERVER")) {
                return "[{\"name\": \"Nadal, Rafael (ESP)\", \"email\": \"[email protected]\", \"rank\": \"1\"},"
                        + "{\"name\": \"Djokovic, Novak (SRB)\", \"email\": \"[email protected]\", \"rank\": \"2\"},"
                        + "{\"name\": \"Federer, Roger (SUI)\", \"email\": \"[email protected]\", \"rank\": \"3\"},"
                        + "{\"name\": \"Wawrinka, Stan (SUI)\", \"email\": \"[email protected]\", \"rank\": \"4\"},"
                        + "{\"name\": \"Ferrer, David (ESP)\", \"email\": \"[email protected]\", \"rank\": \"5\"}]";
            }
        }
        return "";
    }

    @OnOpen
    public void onOpen(Session peer) {
        LOG.info("Connection opened ...");
        peers.add(peer);
    }

    @OnClose
    public void onClose(Session peer) {
        LOG.info("Connection closed ...");
        peers.remove(peer);
    }
}

And, we access this endpoint like this:

  • the client sends a hello message (HELLO SERVER), and the server answers with a simple text (Hello, if you need the ATP list just press the button ...).
  • the client send another message, (ATP SERVER), and the server answers with a JSON object containing a list of tennis players
  • the client will display this list in a table

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" 
                 href="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-csp.css">
        <title>Angular JS Web-Socket</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        
    </head>
    <body ng-app="ATP_PLAYERS" class="ng-cloak">                
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
        <script src="resources/js/angular-websocket.js"></script>

        <div ng-controller="atpController">

            <div id="helloId"></div>

            <form ng-submit="submit()">                
                <button id="btnAtpId" type="submit" disabled>Send Message</button>
            </form>

            <table>
                <thead>
                    <tr>
                        <th>Rank</th>   
                        <th>Name</th>   
                        <th>E-mail</th>   
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in ATP.atp">
                        <td>{{item.rank}}</td>               
                        <td>{{item.name}}</td>
                        <td>{{item.email}}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <script language="javascript" type="text/javascript">
            angular.module('ATP_PLAYERS', ['ngWebSocket'])
                    .factory('ATP', function ($websocket) {
                        // Open a WebSocket connection
                        var ws = $websocket("ws://" + document.location.host + 
                              document.location.pathname + "atpendpoint");
                        var atp = [];

                        ws.onMessage(function (event) {
                            console.log('message: ', event.data);
                            var response;
                            try {
                                response = angular.fromJson(event.data);
                            } catch (e) {
                                document.getElementById("helloId").innerHTML = 
                                                                                   "Sorry, connection failed ...";
                                document.getElementById("btnAtpId").disabled = false;
                                console.log('error: ', e);
                                response = {'error': e};
                            }

                            if (response.hello) {
                                document.getElementById("helloId").innerHTML = response.hello;
                                document.getElementById("btnAtpId").disabled = false;
                            } else {
                                for (var i = 0; i < response.length; i++) {
                                    atp.push({
                                        rank: response[i].rank,
                                        name: response[i].name,
                                        email: response[i].email
                                    });
                                }
                            }
                        });
                        ws.onError(function (event) {
                            console.log('connection Error', event);
                        });
                        ws.onClose(function (event) {
                            console.log('connection closed', event);
                        });
                        ws.onOpen(function () {
                            console.log('connection open');
                            ws.send('HELLO SERVER');
                        });

                        return {
                            atp: atp,
                            status: function () {
                                return ws.readyState;
                            },
                            send: function (message) {
                                if (angular.isString(message)) {
                                    ws.send(message);
                                }
                                else if (angular.isObject(message)) {
                                    ws.send(JSON.stringify(message));
                                }
                            }
                        };
                    })
                    .controller('atpController', function ($scope, ATP) {
                        $scope.ATP = ATP;

                        $scope.submit = function () {
                            ATP.send("ATP SERVER");
                        };                                               
                    });
        </script>
    </body>
</html>

AngularJS WebSocket Java (programming language)

Published at DZone with permission of Anghel Leonard. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  • Faster Releases With DevOps: Java Microservices and Angular UI in CI/CD
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Legacy Code Refactoring: Tips, Steps, and Best Practices

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook