Creating a WebSocket Server with the Java API for WebSockets

Published October 22, 2018 by Steve Crow
Categories:

WebSocket is a protocol which enables communication between the server and the browser. It has an advantage over RESTful HTTP because communications are both bi-directional and real-time. This allows for the server to notify the client at any time instead of the client polling on a regular interval for updates.

In this series of posts, I’m going to show you three different ways to create a WebSocket server in Java using Spring Boot, the Spark Framework, and the Java API for WebSockets.

Prerequisites

You will be using Gradle to manage your dependencies and run your application.

Additionally, you’ll need to make sure you have a copy of the JDK installed. I will be using JDK 8 in this tutorial.

The Java API for WebSockets

Introduced in Java EE 7, the Java API for WebSockets, or JSR 356 is a specification that Java developers can use in order to integrate WebSockets into their applications.

It allows developers to write their WebSocket-based application completely independent of their container’s implementation. For this guide you will be using Tomcat. However, because you will be using JSR 356, any other web container which supports Java EE 7 should work.

Create the Project

You will use Gradle to initialize a new Java application. You can use the following command to create a directory for your project, navigate to that directory, and initialize the application:

Add the Java WebSocket API Dependency

Add the following dependency to the dependencies block of build.gradle:

Create the WebSocket Endpoint

WebSocket messages can be both text and binary. You’re going to create an endpoint that can handle both of these messages.

The @ServerEndpoint annotation is used to decorate a class and declare it as a WebSocket endpoint. You can provide it with a parameter which represents the path that the endpoint is published on.

Create a new class called WebSocketEndpoint and annotate it with @ServerEndpoint("/socket"):

Each event that the WebSocketEndpoint handles is defined by an annotation. You can use the @OnMessage annotation to tag methods for receiving binary or text events.

For demonstration purposes, you’re going to create an echo server which will echo the message received back to the sender.

In order to test binary messages, you will be sending images to the WebSocket server. The default max size depends on the container, but you can use the maxMessageSize parameter to specify how large of a message to support.

Add the following methods:

Note that the method signature determines which type of message the method will handle. See the OnMessage annotation documentation for a list of supported method signatures.

Create a Client to Test Your Application

You will need to create a client to test your WebSocket server. You will want to test sending both text and binary messages. This can be accomplished with JavaScript.

Create the webapp folder inside of the src/main folder.

Add the following to index.html inside of the src/main/webapp folder:

Embed and Configure Tomcat

Unlike Creating a WebSocket Server with Spring Boot, or Creating a WebSocket Server with the Spark Framework, there is initially no embedded server to run your application.

The Gretty plugin for Gradle can be used to embed a variety of containers.

First, apply the Gretty plugin to build.gradle file by adding this to your plugins block:

Second, you will need to configure Gretty to use Tomcat as the servlet container, and set the context path to / for the sake of simplicity.

Add the following block to build.gradle:

Note that, by default, Gretty will use Jetty as the servlet container. This same guide will also run in Jetty, but that is the same container that both Spring Boot and the Spark framework embed and I wanted to show something different.

Start the Application

Your WebSocket server is now complete. Start your application using the gradle appRun command inside of the application’s directory.

You can access your application at http://localhost:8080 where you will be greeted with the following page:

Sample JavaScript-enabled client for testing the WebSocket server.

The “connected” message indicates that the JavaScript client was able to make a connection.

Try sending a text message by typing into the input field and clicking on the send button. Also try uploading an image. In both instances, you should see the same message and image echoed back.

Sample JavaScript-enabled client showing a text and binary message echoed back.

Conclusion

In this tutorial you learned how to create a WebSocket server using JSR 356 which can receive both binary and text messages and run on any JSR 356 compliant container. Try removing the servletContainer setting and running in Jetty, or use the Gradle WAR plugin to generate a WAR file and deploy it on a different container.

The finished code for this tutorial can be found on the nexmo-community/websocket-java-api repository.

Did you know that you can use WebSocket as an endpoint in a Nexmo Call Control Object? Check out this post on Real Time Call Transcription with IBM Watson to learn how to use the Nexmo Voice API, WebSockets, and IBM Watson to perform real-time call transcription.

Interested in reading more about WebSockets? Check out this post on What are WebSockets? How Can They Enhance Digital Solutions?

Leave a Reply

Your email address will not be published.