How to make Basic Web Socket with spring

How to make Basic Web Socket with spring


4 min read


Unlike, HTTP, web socket allow both client and server to communicate with each other, independently at the same time. Web socket is an event -driven protocol, and it is use for real time communication. Web Sockets keeps a single, persistent connection open while eliminating latency problems. web socket is a stateful protocol which means connection between client and server will always keep alive until and unless terminates by either side. TCP is foundation for web socket. Either client or server initiate connection , called handshake. Messages can by send bi-directional. All the modern browser supports web socket. Some of the use of web socket are:-
social feeds
multiplayer game
update of game/tournament
collaborative editing
online education


You are going to create simple web socket app

Software Requirements:-

Ubuntu-20.04 +jit [linux-x86_64]
Open Jdk 8
Spring Boot 2.2




Knowledge of core java and text editor/NetBeans IDE

Step 1:-

Adding Maven Dependencies
complete pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""


  <description>Spring Boot: user notifications with web socket</description>

    <relativePath />



    <!-- Spring Security -->

    <!-- Web Sockets -->




Step 2:-


public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

   * Register Stomp endpoints: the url to open the WebSocket connection.
  public void registerStompEndpoints(StompEndpointRegistry registry) {



@EnableWebSocketMessageBroker enable broker-backed messaging over Web Socket using a higher-level messaging sub-protocol.

Register the "/ws" endpoint, enabling the SockJS protocol.

SockJS is used (both client and server side) to allow alternative messaging options if WebSocket is not available.

The registerStompEndpoints method registers the “/ws” endpoint, enabling Spring’s STOMP support. This endpoint, when prefixed with “/app”, is the endpoint that the ChatController.send() method is mapped to handle.

It also enables the SockJS fallback options, so that alternative messaging options may be used if WebSockets are not available.

The fallbacks let the applications use a WebSocket API but gracefully degrade to non-WebSocket alternatives when necessary at runtime.

Step 3:-


public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  public void configureGlobal(AuthenticationManagerBuilder auth)
  throws Exception {
      // Defines three users with their passwords and roles

Enable authentication with three in-memory users: DevNation, ServerNation and EngineersNation. Spring Security will provide a default login form where insert username and password.

Step 4:-

Create a Message-handling Controller

To configure the mapping of web requests, you use the @RequestMapping annotation.

The @RequestMapping annotation can be applied to class-level and/or method-level in a controller.

The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.

public class MainController {

  private SocketificationService socketificationService;

   * GET  /  -> show the index page.
  public String index() {
    return "index";

   * GET  /socketifications  -> show the socketifications page.
  public String socketifications() {
    return "socketifications";
    // Send the socketification to "DevNation" (by username)  
      new Socketification("SpringbootWebSocket"), // socketification object
      "DevNation"                    // username

Step 5:-

Create a Browser Client
After making your configurations in the server-side, you'll use the sockjs-client library to build a simple HTML page that interacts with our messaging system. you will import sockjs and stomp Javascript client libraries.

<!DOCTYPE html>
<html xmlns="" xmlns:th=""
    <script src="//"></script>
    <script src="sockjs-0.3.4.min.js"></script>
    <script src="stomp.min.js"></script>
    <p th:inline="text">
      You are logged as: <b>[[${#httpServletRequest.remoteUser}]]</b>
      (<a href="/logout">logout</a>)
      Click the button below to perform an action.
      <br />
      <strong>DevNation</strong> will be socketified via web socket.
    <input id="do-some-action" type="button" value="Click me" />

    <!-- Javascript functions -->
       * Send an action to the server.
      function sendAction(event) {
          url: "/some-action",
          type: "POST"
      } // function sendAction

       * Init operations.
      $(document).ready(function() {

        // Bind the on-click event for the button element.
        $("#do-some-action").on("click", sendAction);


      <br />
    <hr />

Step 6:-

Run the App
$ mvn spring-boot:run




Folder Structure-



After performing above steps, you make a basic web socket app with spring boot. In this tutorial, you've explored Spring's WebSocket support. you've seen its server-side configuration and built a simple client-side counterpart with the use of sockjs and stomp Javascript libraries.