If you’re working with Spring, check out "REST With Spring":

>> CHECK OUT THE COURSE

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 article, we’ll take a look at 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 withing 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

We will build a very simple chat-like application. Any user will be able to open the chat from any browser, type his name, login 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>

The latest version may be found 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. You can either extend the javax.websocket.Endpoint class or use dedicated method-level annotations. As the annotation model leads to cleaner code as compared to the programmatic model, the annotation has become the conventional choice of coding. In this case, WebSocket endpoint lifecycle events are handled by the following annotations:

  • @ServerEndpoint: If decorated with @ServerEndpoint, the container ensures 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 is a problem with the communication
  • @OnClose: Used to decorate a Java method that is called by the container when the WebSocket connection closes

3.2. Writing the Server Endpoint

We declare a Java class WebSocket server endpoint by annotating it with @ServerEndpoint. We also specify the URI where the endpoint is deployed. The URI is defined relatively to the root of the server container and 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 you can see, we have 4 annotations mapped to their respective methods. Below you 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. You 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 these formats, adds capabilities to work with Java objects and health check 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 your 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<T> or Encoder.Binary<T> interfaces.

In the code below we define the class Message to be encoded and in the method encode we 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 and is used to transform data back into a Java object. Decoders can be implemented using the Decoder.Text<T> or Decoder.Binary<T> interfaces.

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 will automatically either be converted to JSON or Java objects.

5. Conclusion

In this article, we looked at what is the Java API for WebSockets  and how it can help us building applications such as this real-time chat.

We saw the two programming models for creating an endpoint: annotations and programmatic. 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 saw 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 that 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/. You can find the link to the repository here.

The new Certification Class of "REST With Spring" is finally out:

>> CHECK OUT THE COURSE

Sort by:   newest | oldest | most voted
Marcos Cespedes
Guest

great post !

Richard Cowin
Guest

Thanks, a nice intro to Web Sockets. I presume the Message class is just a POJO with username and content properties as Strings?

Grzegorz Piwowarek
Guest

Yes, you can find it here: https://github.com/eugenp/tutorials/blob/c83c449fa5a7ac2462fabf0ed26969f1b037aa12/java-websocket/src/main/java/com/baeldung/model/Message.java

Actually, we will update the article and include this one. Thanks!

wpDiscuz