Simple websocket demo

Time:2021-7-29

There are two ways to use websocket: one is to use sockjs, and the other is to use H5 standard. The use of HTML5 standard is naturally more convenient and simple, so the use method matched with H5 is recorded.

  1. pom

    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
  2. Create a websocket endpoint using @ serverendpoint
    First, inject the serverendpointexporter. This bean will automatically register the websocket endpoint declared with the @ serverendpoint annotation. Note that if you use a separate servlet container instead of directly using the spring boot built-in container, do not inject the server endpoint exporter, as it will be provided and managed by the container itself.

    @Configuration
    public class WebSocketConfig {
    
     @Bean
     public ServerEndpointExporter serverEndpointExporter(){
         return new ServerEndpointExporter();
     }
    }

    The next step is to write the specific implementation class of websocket, and directly the code:

    @Component
    @ServerEndpoint("/websocket")
    public class MyWebSocket {
     //The connection session with a client needs to send data to the client through it
     private Session session;
     //The thread safe set of the concurrent package is used to store the mywebsocket object corresponding to each client.
     private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
    
     @OnOpen
     public void onOpen(Session session){
         this.session = session;
         webSocketSet.add(this);
         System. Out. Println ("create connection: section" + websocketset. Size());
     }
    
     @OnClose
     public void onClose(){
         webSocketSet.remove(this);
         System.out.println ("close connection");
     }
    
     @OnMessage
     public void onMessage(String message){
         System. Out. Println ("accept client message:" + message);
     }
    
     /**
      *Mass messaging
      */
     public void sendMessage(String message){
         for (MyWebSocket myWebSocket : webSocketSet){
             try {
                 myWebSocket.session.getBasicRemote().sendText(message);
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     //A single message can be transformed on the basis of mass sending
    }

    The only difference between using springboot and using the @ component declaration is that the websocket is managed by the container itself, but even the container is managed by spring in springboot.
    Although @ component is singleton mode by default, springboot will initialize a bean for each websocket connection, so it can be saved with a static set.

  3. Front end code

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
     <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     < title > Home Page < / Title >
    </head>
    <body>
    <script type="text/javascript" th:inline="javascript">
     var websocket = null;
     if('WebSocket' in window){
         //127.0.0.1:8080 is the project request address. Websocket is the corresponding value in @ serverendpoint ("/ websocket"). Together, it is the request websocket address
         websocket = new WebSocket('ws://127.0.0.1:8080/websocket');
     }else{
         Alert ("this browser does not support websocket!")
     }
     websocket.onopen = function (event) {
         Console.log ("establish connection");
     }
     websocket.onclose = function (event) {
         Console.log ("close connection");
     }
     websocket.onmessage = function (event) {
         Console.log ("accept message:" + event. Data);
         //Simulate sending information to the server
         Websocket. Send ("I have received the message!")
     }
     websocket.onerror = function (event) {
         Console.log ("an error occurred")
     }
     window.onbeforeunload = function () {
         websocket.onclose();
     }
    </script>
    </body>
    </html>
  4. test method

    @RestController
    @RequestMapping("/testWebSocketSend")
    public class TestWebSocketSendController {
     @Autowired
     private MyWebSocket myWebSocket;
     @GetMapping("send")
     public String send(@RequestParam("message") String message){
         //Todo other business
         //Websocket service
         myWebSocket.sendMessage(message);
         Return "success";
     }
    }

    Open master page127.0.0.1:8080/index.html
    Simple websocket demo
    Browser request127.0.0.1:8080/testWebSocketSend/se…The controller address I wrote before
    Simple websocket demo
    The server accepts the message printing of the client
    Simple websocket demo

This work adoptsCC agreement, reprint must indicate the author and the link to this article