1. Overview
WebSocket provides an alternative to the limitation of efficient communication between the server and the web browser by providing bi-directional, full-duplex, real-time client/server communications. The server can send data to the client at any time. Because it runs over TCP, it also provides a low-latency, low-level communication, and reduces the overhead of each message**.**
In this tutorial, we’ll explore the Java API for WebSockets by creating a chat-like application.
2. JSR 356
JSR 356, or the Java API for WebSocket, specifies an API that Java developers can use for integrating WebSockets within their applications, both on the server side, as well as on the Java client side.
This Java API provides both server and client side components:
- Server: everything in the javax.websocket.server package
- Client: the content of javax.websocket package, which consists of client side APIs, and also common libraries to both server and client
3. Building a Chat Using WebSockets
Let’s build a very simple chat-like application. Any user will be able to open the chat from any browser, type their name, log into the chat, and start communicating with everybody connected to the chat.
We’ll start by adding the latest dependency to the pom.xml file:
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
We can find the latest version here.
In order to convert Java Objects into their JSON representations, and vice versa, we’ll use Gson:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
The latest version is available in the Maven Central repository.
3.1. Endpoint Configuration
There are two ways of configuring endpoints: *annotation-*based and extension-based. We can either extend the javax.websocket.Endpoint class, or use dedicated method-level annotations. As the annotation model leads to cleaner code compared to the programmatic model, the annotation has become the conventional choice of coding. We’ll handle WebSocket endpoint lifecycle events with the following annotations:
- @ServerEndpoint: If decorated with @ServerEndpoint, the container ensures the availability of the class as a WebSocket server listening to a specific URI space.
- @ClientEndpoint: A class decorated with this annotation is treated as a WebSocket client.
- @OnOpen: A Java method with @OnOpen is invoked by the container when a new WebSocket connection is initiated.
- @OnMessage: A Java method annotated with @OnMessage receives the information from the WebSocket container when a message is sent to the endpoint.
- @OnError: A method with @OnError is invoked when there’s a problem with the communication.
- @OnClose: Used to decorate a Java method that’s called by the container when the WebSocket connection closes
3.2. Writing the Server Endpoint
We’ll declare a Java class WebSocket server endpoint by annotating it with @ServerEndpoint. We’ll also specify the URI where we’ll deploy the endpoint. We define the URI relative to the root of the server container, and it must begin with a forward slash:
@ServerEndpoint(value = "/chat/{username}")
public class ChatEndpoint {
@OnOpen
public void onOpen(Session session) throws IOException {
// Get session and WebSocket connection
}
@OnMessage
public void onMessage(Session session, Message message) throws IOException {
// Handle new messages
}
@OnClose
public void onClose(Session session) throws IOException {
// WebSocket connection closes
}
@OnError
public void onError(Session session, Throwable throwable) {
// Do error handling here
}
}
The code above is the server endpoint skeleton for our chat-like application. As we can see, we have four annotations mapped to their respective methods. Below, we can see the implementation of such methods:
@ServerEndpoint(value="/chat/{username}")
public class ChatEndpoint {
private Session session;
private static Set<ChatEndpoint> chatEndpoints
= new CopyOnWriteArraySet<>();
private static HashMap<String, String> users = new HashMap<>();
@OnOpen
public void onOpen(
Session session,
@PathParam("username") String username) throws IOException {
this.session = session;
chatEndpoints.add(this);
users.put(session.getId(), username);
Message message = new Message();
message.setFrom(username);
message.setContent("Connected!");
broadcast(message);
}
@OnMessage
public void onMessage(Session session, Message message)
throws IOException {
message.setFrom(users.get(session.getId()));
broadcast(message);
}
@OnClose
public void onClose(Session session) throws IOException {
chatEndpoints.remove(this);
Message message = new Message();
message.setFrom(users.get(session.getId()));
message.setContent("Disconnected!");
broadcast(message);
}
@OnError
public void onError(Session session, Throwable throwable) {
// Do error handling here
}
private static void broadcast(Message message)
throws IOException, EncodeException {
chatEndpoints.forEach(endpoint -> {
synchronized (endpoint) {
try {
endpoint.session.getBasicRemote().
sendObject(message);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
});
}
}
When a new user logs in, (@OnOpen) is immediately mapped to a data structure of active users. Then a message is created and sent to all endpoints using the broadcast method.
This method is also used whenever a new message is sent (@OnMessage) by any of the users connected; this is the main purpose of the chat.
If at some point an error occurs, the method with the annotation @OnError handles it. We can use this method to log the information about the error, and clear the endpoints.
Finally, when a user is no longer connected to the chat, the method @OnClose clears the endpoint, and broadcasts to all users that a user has been disconnected.
4. Message Types
The WebSocket specification supports two on-wire data formats, text and binary. The API supports both of these formats, adds capabilities to work with Java objects, and health checks messages (ping-pong), as defined in the specification:
- Text: Any textual data (java.lang.String, primitives, or their equivalent wrapper classes)
- Binary: Binary data (e.g. audio, image etc.) represented by a java.nio.ByteBuffer or a byte[] (byte array)
- Java objects: The API makes it possible to work with native (Java object) representations in our code and use custom transformers (encoders/decoders) to convert them into compatible on-wire formats (text, binary) allowed by the WebSocket protocol
- Ping-Pong: A javax.websocket.PongMessage is an acknowledgment sent by a WebSocket peer in response to a health check (ping) request
For our application, we’ll be using Java Objects. We’ll create the classes for encoding and decoding messages.
4.1. Encoder
An encoder takes a Java object and produces a typical representation suitable for transmission as a message, such as JSON, XML, or binary representation. Encoders can be used by implementing the Encoder.Text
In the code below, we’ll define the class Message that we’ll encode, and in the method encode, we’ll use Gson for encoding the Java object to JSON:
public class Message {
private String from;
private String to;
private String content;
//standard constructors, getters, setters
}
public class MessageEncoder implements Encoder.Text<Message> {
private static Gson gson = new Gson();
@Override
public String encode(Message message) throws EncodeException {
return gson.toJson(message);
}
@Override
public void init(EndpointConfig endpointConfig) {
// Custom initialization logic
}
@Override
public void destroy() {
// Close resources
}
}
4.2. Decoder
A decoder is the opposite of an encoder. We use it to transform data back into a Java object. Decoders can be implemented using the Decoder.Text
As we saw with the encoder, the decode method is where we take the JSON retrieved in the message sent to the endpoint, and use Gson to transform it to a Java class called Message:
public class MessageDecoder implements Decoder.Text<Message> {
private static Gson gson = new Gson();
@Override
public Message decode(String s) throws DecodeException {
return gson.fromJson(s, Message.class);
}
@Override
public boolean willDecode(String s) {
return (s != null);
}
@Override
public void init(EndpointConfig endpointConfig) {
// Custom initialization logic
}
@Override
public void destroy() {
// Close resources
}
}
4.3. Setting Encoder and Decoder in Server Endpoint
Let’s put everything together by adding the classes created for encoding and decoding the data at the class level annotation @ServerEndpoint:
@ServerEndpoint(
value="/chat/{username}",
decoders = MessageDecoder.class,
encoders = MessageEncoder.class )
Every time messages are sent to the endpoint, they’ll automatically be converted to either JSON or Java objects.
5. Conclusion
In this article, we analyzed the Java API for WebSockets, and learned how it can help us in building applications, such as this real-time chat.
We discussed the two programming models for creating an endpoint: annotations and programmatic. Then we defined an endpoint using the annotation model for our application, along with the life cycle methods.
Also, in order to be able to communicate back and forth between the server and client, we demonstrated that we need encoders and decoders to convert Java objects to JSON, and vice versa.
The JSR 356 API is very simple, and the annotation based programming model makes it very easy to build WebSocket applications.
To run the application we built in the example, all we need to do is deploy the war file in a web server, and go to the URL: http://localhost:8080/java-websocket/. The link to the repository can be found here.