Spring Boot + Websocket Example

Let us again walk through creating websocket connection in spring boot but this time with STOMP protocol. We will be creating a sample example project to perform all the communications over websocket protocol between a client and a server. We will also integrate Spring security to secure our websocket connections that restricts websocket server reply to a single client(queue) instead of broadcasting to all clients(topic). Here, we will be using spring boot configurations to configure websocket connection with STOMP, sockJS and spring security.

What is WebSocket

Like http, websocket is also a communication protocol which provides bi-directional, full-duplex communication channel between a server and client. Once, a WebSocket connection is established between a client and a server, both the parties can exchange information endlessly until the connection is closed by anyone of the parties.

This is the main reason why WebSocket is preferred over HTTP where the client and server need to exchange information at high frequency and with low latency because HTTP connection is closed once a request is served by the server and there is a time constraint to open an HTTP connection again.

Also, the WebSocket protocol is bi-directional i.e. a client can subscribe for some event and server can publish the event to the client based on the availability of the event in the server.

While talking about WebSocket, let us also talk about Server Sent Events introduced in HTML 5. Many times, we may not really require WebSocket connection and these server sent events might serve our purpose.

Server-Sent Events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection. In a server-sent event, a web page automatically gets updates from a server and the server produces the response in a text/event-stream format.

What is STOMP

STOMP stands for Streaming Text Oriented Messaging Protocol. As per wiki, STOMP is a simple text-based protocol, designed for working with message-oriented middleware (MOM).

STOMP provides an interoperable wire format that allows STOMP clients to talk with any message broker supporting the protocol.Spring provides default support for it but you are open to choose any other messaging protocol such as RabbitMQ or ActiveMQ.

Spring Boot Websocket Project Setup

1. JDK 8

2. Spring Boot

3. Intellij Idea/ eclipse

4. Tomcat(embedded with Spring)

5. Maven

Maven Dependencies

Below is the maven dependencies that we require to get started with this example.

Spring Boot Websocket Configuration

Below are the steps that we will follow to integrate websocket with spring boot app.

Register STOMP endpoint at /greeting. This endpoint will be used by the client app (app.js) to connect to STOMP.

Next, Enable a simple message broker and configure one or more prefixes to filter destinations targeting the broker (e.g. destinations prefixed with "/topic"). The client app will subscribe mesages at endpoints starting with these configured endpoint.

Now, set application destination prefixes e.g. /app. The client will send messages at this endpoint. For example, if client sends message at /app/message, the endpoint configured at /message in the spring controller will be invoked.

After these configuration steps, we can write our controller class to start the communication over websocket protocol. Now, let us implement this steps in spring boot app.

First of all let us configure our STOMP message broker. In WebSocketConfig.java we have defined our message broker STOMP endpoint and websocket application endpoint.

@Configuration : It indicates that it is a Spring configuration class.

@EnableWebSocketMessageBroker : It enables WebSocket message handling, backed by a message broker. Here we are using STOMP as a mesage broker.

The method configureMessageBroker() enables a simple memory-based message broker to carry the messages back to the client on destinations prefixed with "/topic" and "/queue".

It also designates the "/app" prefix for messages that are bound for @MessageMapping-annotated methods in controller class. This prefix will be used to define all the message mappings; for example, "/app/message" is the endpoint that the WebSocketController.processMessageFromClient() method is mapped to handle.

Similarly,registerStompEndpoints() enables STOMP support and registers stomp endoints at "/greeting".Doing so, all the websocket messages will be channelised through STOMP and this also adds an extra layer of security to the websocket endpoint.

Remember that, while creating websocket connection from javascipt, we will be using this particular stomp endpoint only.

In the configuration below to enable SockJs support to provide deafult falback option, we need to make following changes.

registry.addEndpoint("/greeting").withSockJS();

The advantage of using sockJS here is whenever the websocket connection is disconnected or the websocket connection can not be established,then the connection will be downgraded to HTTP and the communication between client and server can still continue.

Websocket Listeners and Interceptors

Apart from above configuration, spring boot also provides mechanism to register different listeners or interceptors and this configuration can be added in registerStompEndpoints() methods defined above.

Websocket Endpoint

Now let us define our controller and map the websocket connection endpoint.

@MessageMapping: This isto map the message headed for the url /message

@SendToUser: indicates that the return value of a message-handling method should be sent as a org.springframework.messaging.Message to the specified destination(s) prepended with "/user/{username}" where the user name is extracted from the headers of the input message being handled.

@MessageExceptionHandler: throw any exceptions caused by STOMP to the end user on the /queue/errors destination.

@Payload: to extract the payload of a message and optionally convert it using spring MessageConverter.

convertAndSendToUser() facilitates same operation as of @SendToUser.This is used when you want to send message to a particular user and this message will be sent to a queue. There is also convertAndSend() which will broadcast message to a topic.

WebSocket Authentication

WebSockets reuse the same authentication information that is found in the HTTP request when the WebSocket connection was made. This means that the Principal on the HttpServletRequest will be handed off to WebSockets

Hence, in our controller method, we have principal object injected. The application sends the message to the recipient using

We wll be using spring boot feature to run our application. The spring boot maven plugin will collect all the jars on the classpath and builds a single, runnable jar file, which makes it more convenient to execute and transport our service. It searches for the public static void main() method to flag as a runnable class and provides built-in dependency resolver that sets the version number to match spring boot dependencies.

SpringBootServletInitializer enables process used in Servlet 3.0 using web.xml

@SpringBootApplication: This is a convenience annotation that is equivalent to declaring @Configuration,@EnableAutoConfiguration and @ComponentScan.

Websocket SockJS Config

To make use of SockJS in the client code you require to include sockjs.js in html.SockJS provides best available fallback options whenever websocket connection fails or unavailable.Following is the sample code to make use of it while establishing websocket connection from client.

var socket = new SockJS('ws://localhost:8080/greeting');
ws = Stomp.over(socket);
//rest of the code as usual as above

we have a .html file to trigger the WebSocket connection over a button click. The text entered in the text box will be sent to server over websocket protocol and the response from the server will be diaplayed in the Greetings div element.

Run Websocket Application

2. Open the browser and hit the URL - http:localhost:8080. It will prompt for username and password as below.By default the username is user and password you can check in the console.

3. Now, you can see the index.html after successful authentication.

4. Click on connect button to make the socket connection.

5. Enter the name and post the message and you can see the greeting message as below from websocket server.

Conclusion

In this article we learned about spring boot websocket configuration and implemenation.I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.