Real-Time Communication: Implementing Websockets With Spring Boot

DZone 's Guide to

Real-Time Communication: Implementing Websockets With Spring Boot

In this article, we’ll introduce you to the Websockets API and show you how to implement Websockets with the Spring Boot platform.

· Web Dev Zone ·
Free Resource

When developing web applications, we sometimes need to push server events down to connected clients. However, HTTP was not designed to allow this. A client opens a connection to a server and requests data. A server does not open a connection to a client and push data.

To get around this limitation, a polling pattern was established where web pages would intermittently poll the server for any new events. This pattern was not ideal as it added HTTP overhead, was only as fast as the polling rate and caused unnecessary load on the server.

Luckily, with the emergence of HTML5 came the WebSocket. The WebSocket protocol enables interaction between a browser and a web server with lower overheads. In this blog, we’ll introduce the Websockets API and show how to implement Websockets with Spring Boot.

HTML5 to the Rescue!

WebSockets provide full-duplex communication over a single connection between the browser and the server. It does not have the overhead of HTTP and allows the server to push messages to the client in real-time.

The WebSocket API is actually quite simple. Create a WebSocket object, attach event listeners, and send messages.

Here is an example:

var socket = new WebSocket('ws://' + window.location.host + '/my-websocket-endpoint');

// Add an event listener for when a connection is open
socket.onopen = function() {
  console.log('WebSocket connection opened. Ready to send messages.');

  // Send a message to the server
  socket.send('Hello, from WebSocket client!');

// Add an event listener for when a message is received from the server
socket.onmessage = function(message) {
  console.log('Message received from server: ' + message);

Spring Boot

Spring has excellent support for interfacing with WebSockets.

First, we need to create a class that extends the Spring class TextWebSocketHandler .

public class MyMessageHandler extends TextWebSocketHandler {

    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // The WebSocket has been closed

    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // The WebSocket has been opened
        // I might save this session object so that I can send messages to it outside of this method

        // Let's send the first message
        session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));

    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        // A message has been received
        System.out.println("Message received: " + textMessage.getPayload());

Next, we need to configure our WebSocket endpoint.

public class WebsocketConfig implements WebSocketConfigurer {

    public WebSocketHandler myMessageHandler() {
        return new MyMessageHandler();

    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");


Since the WebSockets API is pure JavaScript, you should be able to use it in most front-end frameworks. This includes Angular, as you can include JavaScript right in there with the TypeScript.

Final Thoughts

Pretty simple, and it solves a big headache in regards to the transfer of data between the server and client simultaneously. Spring Boot makes it even easier.

Want to see Websockets in action? At Keyhole, we have built an open source tool, Trouble Maker, that injects failures into our platform so that we can exercise and test the recovery mechanisms that make the platform resilient. Trouble Maker has an Angular front-end and utilizes WebSockets for some real-time communication. Check out the Github Repo to try it in action.

web dev ,http ,websocket api

Published at DZone with permission of Thomas Kendall , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}