Over a million developers have joined DZone.

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.

· Java Zone

Learn more about the advantages of moving from a monolithic to microservices architecture.  Brought to you in partnership with IBM.

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;

public class ATPWSEndpoint {

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

    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\": \"nadalrafael@gmail.com\", \"rank\": \"1\"},"
                        + "{\"name\": \"Djokovic, Novak (SRB)\", \"email\": \"djokovicnovak@gmail.com\", \"rank\": \"2\"},"
                        + "{\"name\": \"Federer, Roger (SUI)\", \"email\": \"federerroger@gmail.com\", \"rank\": \"3\"},"
                        + "{\"name\": \"Wawrinka, Stan (SUI)\", \"email\": \"wawrinkastan@gmail.com\", \"rank\": \"4\"},"
                        + "{\"name\": \"Ferrer, David (ESP)\", \"email\": \"ferrerdavid@gmail.com\", \"rank\": \"5\"}]";
        return "";

    public void onOpen(Session peer) {
        LOG.info("Connection opened ...");

    public void onClose(Session peer) {
        LOG.info("Connection closed ...");

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>
        <link rel="stylesheet" type="text/css" 
        <title>Angular JS Web-Socket</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        
    <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>

                    <tr ng-repeat="item in ATP.atp">

        <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++) {
                                        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)) {
                                else if (angular.isObject(message)) {
                    .controller('atpController', function ($scope, ATP) {
                        $scope.ATP = ATP;

                        $scope.submit = function () {
                            ATP.send("ATP SERVER");

From Idea to Application gives you the architecture to quickly build, manage and run a range of applications (web, mobile, big data, new smart devices, etc.) on an open-standard, cloud-based platform. See why developers are using IBM Bluemix. Brought to you in partnership with IBM.

java,html5,javascript,tips and tricks,angular js

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}