Purpose

how to create an application that uses the WebSocket API for real-time communication between a client and a server:
  • Create a Java Platform, Enterprise Edition 7 (Java EE 7) application that uses the WebSocket API
  • Use the OnOpen and OnMessage WebSocket lifecycle events to perform different actions on the Java EE 7 application.
  • Define a client-side WebSocket endpoint by using JavaScript
  • Operate on Plain Old Java Objects (POJOs), in real-time, with actions invoked from a web browser client

Introduction

Modern web applications require more interactivity than ever before for client/server communications. HTTP, however, wasn't built to deliver the kind of interactivity needed today. "Push" or Comet techniques, such as long-polling, emerged as a way to allow a server to push data to a browser. Because these techniques usually rely on HTTP, they present some disadvantages for client/server communications, such as HTTP overhead. These disadvantages result in less efficient communication between the server and the web browser, especially for real-time applications.
WebSocket provides an alternative to this limitation by providing bi-directional, full-duplex, real-time, client/server communications. The server can send data to the client at any time. Because WebSocket runs over TCP, it also reduces the overhead of each message. WebSocket also provides greater scalability for message-intensive applications because only one connection per client is used (whereas HTTP creates one request per message). Finally, WebSocket is part of Java EE 7, so you can use other technologies in the Java EE 7 stack.

Scenario

In this tutorial, you create Java WebSocket Home, a smart home control web application based on Java EE 7. Java WebSocket Home has a user interface for connecting and controlling fictitious devices from a web browser to a Java application. This application provides real-time updates to all clients that are connected to the Java WebSocket Home server.

Software Requirements

The following is a list of software requirements needed for this tutorial:

Prerequisites

Before starting this tutorial, you should have:

  • Knowledge of the Java programming language
  • Basic knowledge of Java EE 7
  • Basic knowledge of HTML 5, JavaScript, and cascading style sheets (CSS)

Introduction to the WebSocket API in Java EE 7

Introduced as part of the HTML 5 initiative, the WebSocket protocol is a standard web technology that simplifies communication and connection management between clients and a server. By maintaining a constant connection, WebSocket provides full-duplex client/server communication. It also provides a low-latency, low-level communication that works on the underlying TCP/IP connection.
The Java API for WebSocket (JSR-356) simplifies the integration of WebSocket into Java EE 7 applications.
Here are some of the features of the Java API for WebSocket:
  • Annotation-driven programming that allows developers to use POJOs to interact with WebSocket lifecycle events
  • Interface-driven programming that allows developers to implement interfaces and methods to interact with WebSocket lifecycle events
  • Integration with other Java EE technologies (You can inject objects and Enterprise JavaBeans by using components such as Contexts and Dependency Injection.)

Creating a Java EE 7 Project

new WebsocketHome web project using Netbeans IDE.

Creating the Device Model

create org.example.model.Device.java with some attributes.

Creating the WebSocket Server Endpoint

create org.example.websocket.DeviceWebSocketServer.java file.

Creating the Session Handler

create org.example.websocket.DeviceSessionHandler.java file
with following methods:
  • addDevice() - Add a device to the application.
  • removeDevice() - Remove a device from the application.
  • toggleDevice() - Toggle the device status.
  • getDevices() - Retrieve the list of devices and their attributes.
  • getDeviceById() - Retrieve a device with a specific identifier.
  • createAddMessage() - Build a JSON message for adding a device to the application.
  • sendToSession() - Send an event message to a client.
  • sendToAllConnectedSessions() - Send an event message to all connected clients.

Rendering the User Interface

create the Java WebSocket Home user interface (UI) by using HTML5 and CSS.

  1. Modify the index.html file.
  2. Create style.css file

Creating the WebSocket Client Endpoint

create websocket.js file.

The file performs the following actions:

  • Maps the WebSocket server endpoint to the URI defined in "Creating the WebSocket Server Endpoint".
  • Captures the JavaScript events for adding, removing, and changing a device's status and pushes those events to the WebSocket server. These methods are addDevice(), removeDevice(), and toggleDevice(). The actions are sent in JSON messages to the WebSocket server.
  • Defines a callback method for the WebSocket onmessage event. The onmessage event captures the events sent from the WebSocket server (in JSON) and processes those actions. In this application, these actions are usually rendering changes in the client UI.
  • Toggles the visibility of an HTML form for adding a new device.

Processing WebSocket Events in the Server

implements functions in DeviceWebSocketServer class.

Implementing the WebSocket Actions in the Session Handler

implements functions in DeviceSessionHandler.java class.

Testing the Java WebSocket Home Application

do add/remove device from one client, the others clients will change immediately.


Summary

You created a smart home control web application by using Java EE 7 and the WebSocket API.
You also learned how to:

  • Define a WebSocket server endpoint in a Java class by using the WebSocket API annotations
  • Send messages to and from the client to the WebSocket server in JSON
  • Use the WebSocket API lifecycle annotations to handle WebSocket events
  • Process WebSocket lifecycle events in the client by using HTML5 and JavaScript

Reference documents

https://spring.io/guides/gs/messaging-stomp-websocket/