Suggested keywords:
  • Java
  • Docker
  • Git
  • React
  • NextJs
  • Spring boot
  • Laravel

WebSocket implementation with Spring Boot

  • Share this:

Spring Boot is a microservice-based Java framework used to create web application. It provides radically faster and widely accessible getting-started experience for the development along with ready to use non functional features. It is licensed under Apache License 2.0.


The WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

It will be persistent connection to send and receive messages quickly between client and server without much overhead.It can be used for Chat Applications, Long Polling Applications, Multi-player Game Applications, Send live Analytics data.

Getting Started

In this article we will create a spring boot application using Maven and send some sample messages from client and server and receive vice versa. Create pom.xml with following dependencies inside the project dir

      mkdir springwebsocket
      cd springwebocket


In the pom.xml, we need to keep spring boot starter parent to create a spring boot project. We would require spring boot starter web for having the http endpoints. It will initially do a handshake on the http endpoints and then web socket protocol is used for future communications. Websocket related dependency are also added for sending and receiving the message in the back end.

Also spring boot maven plugin to make compile and executable jar.


  <?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="" xmlns:xsi=""
   <!-- Additional lines to be added here... -->
    <!-- Package as an executable jar -->

Now we will create the spring boot application starter in the main class using This will create the spring web context with the tomcat as embedded server container.

  @ComponentScan(basePackages= {"com.nagappan.springwebsocket"})
  public class SpringWebsocket {

      public String home() {
          return "hello world";

      public static void main(String args[]) {, args);

Component package scan has been added for the configuration of those packages automatically. We will now create websocket endpoint ("/my-websocket-endpoint") and register handler for the endpoint with websockethandler registry. The handler should be a sub class extended from WebSocketHandler.

   public class WebSocketConfiguration implements WebSocketConfigurer {

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

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


The MyMessageHandler is responsible to send and receive text messages so we need to extend the handler from TextWebSocketHandler which has listeners for Connection establishment, Closing connections and Handling text messages. Once the connection is established it sends a message to client "You are now connected to the server. This is the first message".

   public class MyMessageHandler extends TextWebSocketHandler {

      public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
          System.out.println("web socket 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 */
         System.out.println("web socket connection established");
         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 {
        System.out.println("Message received: " + textMessage.getPayload());


Client can now connect to websocket with WebSocket Javascript API. Javascript websocket API has event handlers for socket open and message handler. Create a websocket and connect to the websocket endpoint (/my-websocket-endpoint). On the successful socket open handler, send the message to the server through websocket. On successful receive server's message(socket.onmessage handler)and provides support to send message to the server. In this example, an input field is provided where user enters the message which will received by the server and it sends back the message to the client. Those discussion conversion will be displayed in the server message in the label fields.

   <!DOCTYPE html>
   <html lang="en">
   <meta charset="UTF-8">
   <title>Spring web socket tutorial</title>
       var socket = new WebSocket('ws://' + + '/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: ');
           document.getElementById("displaymsg").innerText += "\n" +;

     function sendbtn() {
          let textmsg = document.getElementById("msgtext").value;
          console.log("goint to send message");

     <input id="msgtext" type="text"></input>
     <button onclick="sendbtn()">Send</button>

     <h1>Messages received from server</h1>
     <div style="border-style: solid; border-width: 2px;">
            <label id="displaymsg"></label>

Start the application using "mvn spring-boot:run". Then web client ui show all the message send to server in the below label html element.


Websocket implementation using spring boot



Source code :

DevGroves Technologies

About author
DevGroves Technologies is a IT consulting and services start-up company which is predominately to web technologies catering to static website, workflow based CRM websites, e-commerce websites and reporting websites tailoring to the customer needs. We also support open source community by writing blogs about how, why and where it need to be used for.