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
Newsletter
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

  • Build a Voice Assistant With Gemini Live API
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Avoiding AI Debt as a Team
  • The Three Tiers of Agentic Incident Response: When to Trust AI Autonomy

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Jan. 16, 15 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
40.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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