Implement WebSocket with Spring framework

WebSocket is one of the Socket types, in short, for you to easily imagine WebSocket, it helps us to create a 2-way connection between server-side and client-side in any web application. Once the connection has been established, the client and server can exchange information, the client can send messages to the server, and vice versa. Unlike an HTTP connection, only the client can send a request to the server, the server returns a response, the server cannot send a message to any client on its own. WebSocket is often used in web applications that require the real-time of a certain function. In this tutorial, I will show you how to implement WebSocket in a web application with Spring framework.

First, I will create a new Spring Boot project:

Implement WebSocket with Spring framework

with Web and WebSocket dependency as follows:

Implement WebSocket with Spring framework

to make an example.


Implement WebSocket with Spring framework

Create a new WebSocket server

To initialize a WebSocket server with Spring WebSocket, first, you need to understand some concepts as follows:

The first is about Message Broker, it is a message-oriented middleware server in the middle to deliver messages from requests to topics by pub-sub or queue by point-to-point mechanism. That is, instead of applications sending messages directly to the topic or queue that you often see when working with Message Queue, with Message Broker, messages must go through this Message Broker. Spring uses Message Broker to implement WebSocket behind the sense!

The second one is that I will talk about STOMP. What is STOMP? It stands for Streaming Text Oriented Messaging Protocol, which translates to STOMP is a text-oriented messaging protocol, used by the client and server, after being connected to each other, to exchange information. Spring also supports this protocol in transmitting information between client and server with WebSocket.

OK, now we will declare to create a new WebSocket server!

You need to create a new class to configure WebSocket. This class will implement the WebSocketMessageBrokerConfigurer interface and be annotated with the @EnableWebSocketMessageBroker annotation:

Of course, it also needs to be annotated with the @Configuration annotation for Spring Boot to automatically scan!

There are two methods that we need to implement in this WebSocketConfiguration class: configureMessageBroker() and registerStompEndpoints(). The configureMessageBroker() method with the MessageBrokerRegistry class parameter allows us to configure the Message Broker with the enableSimpleBroker() method:

The parameter of the enableSimpleBroker() method is the prefix of the endpoints that clients can subscribe to and receive messages from the server. This means the endpoint to which clients subscribe must start with the value declared with the enableSimpleBroker() method. Otherwise, our application will not run.

In the above configureMessageBroker() method, I also use the setApplicationDestinationPrefixes() method to define the prefix for the destinations that the client will send messages to the WebSocket server. If you have worked with RESTful Web Service using Spring MVC, you can imagine the purpose of this method like you define a request mapping in the Controller at the class level. Methods that define request URLs will prefix the value of this request mapping.

The registerStompEndpoints() method with the StompEndpointRegistry class parameter is the same as when defining the request URL in the RESTful Web Service, helping us to define the endpoints that the client will use to call and connect to the WebSocket. We use the addEndpoint() method of the StompEndpointRegistry class to add the endpoints you want. For example, I define an endpoint as follows:

Some browsers may not support WebSocket connection such as Chrome browser’s incognito mode. In this case, you can call the withSockJS() method to use other alternatives like xhr-streaming, xhr-polling instead of the default WebSocket connection.

The content of my WebSocketConfiguration class now is as follows:

To handle the message from the client sent to the endpoint we just configured above “/hello”, you can create a new MessageController controller with the following content:

Like the controller in Spring MVC, you can annotate the class handle message from the client with the @Controller annotation, but instead of using the @RequestMapping annotation in the message handle method, we use the @MessageMapping annotation with the value being the value of the endpoint that we use. We have configured in WebSocketConfiguration class, my example is “/hello”.

After the method processes the business logic and returns the result, this result will be sent to the destination the client subscribed to, declared in the @SendTo annotation. Remember that the value declared in the @SendTo annotation must start as the value we declared in the enableSimpleBroker() method above!

Now, if you run the application, look at the log message, you will see that the WebSocket server will start and be ready to receive connections from the client side as follows:

Next, we will code the client to see how WebSocket works!

Create a new client to connect to the WebSocket server

I will write HTML, JavaScript code to simulate sending messages from client to server, and also how the server sends messages to the client.

I will use WebJars to add JQuery, SocketJS client and Stomp WebSocket dependencies as follows:

JQuery makes it easier to write Javascript code, SockJS to work with WebSocket connection and Stomp WebSocket let us work with that STOMP message!

I will create a new HTML page that allows us to enter the user name, press the submit button to send the message to the WebSocket server, and a place to display the results returned from the WebSocket server.

Implement WebSocket with Spring framework

The contents of the index.html file in the src/main/resources/static directory are as follows:

The app.js file is also in the src/main/resources/static directory with the following content:

If you know a little about JQuery, you will understand what my code means: when the browser has loaded the content of the index.html page, my web will automatically connect to the WebSocket server using the SockJS client library and use the library Stomp WebSocket to send STOMP messages. The Stomp Client object will subscribe to “/topic/messages” to receive messages from the WebSocket server.

Stomp Client allows us to send a STOMP message to the WebSocket server using the endpoint “/app/hello” with the value we entered in the textbox.

Every time a message is received from the WebSocket server, the value in the body of this STOMP message will be displayed.

The result when I run the application, enter Khanh in the textbox and press the Send button as follows:

Implement WebSocket with Spring framework

If you open 2 browser windows and do the same operation again, you will also see that both browsers receive messages from the WebSocket server. Mine is as follows:

Implement WebSocket with Spring framework

Add Comment