How to make Basic Web Socket with spring

How to make Basic Web Socket with spring

·

4 min read

Intro:-

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
chat
multiplayer game
update of game/tournament
collaborative editing
online education

Task:-

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

Level:-

Beginner

Prerequisite:-

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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

  <groupId>devnation</groupId>
  <artifactId>spring-boot-web-socket-user-notifications</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring-boot-web-socket-user-notifications</name>
  <description>Spring Boot: user notifications with web socket</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.5.RELEASE</version>
    <relativePath />
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>devnation.Application</start-class>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- Spring Security -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- Web Sockets -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-messaging</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-integration</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

Step 2:-

Configuration

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

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

    return;
  }        
}

@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:-

Security

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth)
  throws Exception {
    auth
      // Defines three users with their passwords and roles
      .inMemoryAuthentication()
      .withUser("DevNation").password("DevNation").roles("USER")
      .and()
      .withUser("EngineersNation").password("EngineersNation").roles("USER")
      .and()
      .withUser("ServerNation").password("ServerNation").roles("USER");
    return;
  }

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.

@Controller
public class MainController {

  @Autowired
  private SocketificationService socketificationService;

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

  /**
   * GET  /socketifications  -> show the socketifications page.
   */
  @RequestMapping("/socketifications")
  public String socketifications() {
    return "socketifications";
  }
    // Send the socketification to "DevNation" (by username)  
    socketificationService.socketify(
      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="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
  <head>
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="sockjs-0.3.4.min.js"></script>
    <script src="stomp.min.js"></script>
  </head>
  <body>
    <p th:inline="text">
      You are logged as: <b>[[${#httpServletRequest.remoteUser}]]</b>
      (<a href="/logout">logout</a>)
    </p>
    <p>
      Click the button below to perform an action.
      <br />
      <strong>DevNation</strong> will be socketified via web socket.
    </p>
    <input id="do-some-action" type="button" value="Click me" />

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

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

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

      });

    </script>
      <br />
    <hr />
  </body>

Step 6:-

Run the App
$ mvn spring-boot:run

ws1.png

ws2.png

ws3.png

Folder Structure-

wsfolderstruct.png

Conclusion:-

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.