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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • Code Play #1: WebSockets With Vert.x and Angular
  • How to Use Bootstrap to Build Beautiful Angular Apps

Trending

  • Run Scalable Python Workloads With Modal
  • Multiple Stakeholder Management in Software Engineering
  • The Evolution of Software Integration: How MCP Is Reshaping AI Development Beyond Traditional APIs
  • Seata the Deal: No More Distributed Transaction Nightmares Across (Spring Boot) Microservices
  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.2K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • Code Play #1: WebSockets With Vert.x and Angular
  • How to Use Bootstrap to Build Beautiful Angular Apps

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: