SpringBoot-WebSocket browser-server two-way communication

Article directory

  • Introduction to WebSockets
  • Getting Started Case

WebSocket Introduction

WebSocket is a new network protocol based on TCP. It realizes full-duplex communication between the browser and the server – the browser and the server only need to complete a handshake, and a persistent connection can be created between the two and bidirectional data transmission can be carried out.


Application scenarios:

  • Video barrage
  • Web chat
  • Live sports updates
  • Real-time updates of stock fund quotations

Getting Started Case

Implementation steps:

  1. Directly use the websocket.html page as a WebSocket client
  2. Import the maven coordinates of WebSocket
  3. Import the WebSocket server component WebSocketServer for communicating with the client
  4. Import the configuration class WebSocketConfiguration and register the server component of WebSocket
  5. Import the scheduled task class WebSocketTask to push data to the client regularly

websocket.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
</head>
<body>
    <input id="text" type="text" />
    <button onclick="send()">Send message</button>
    <button onclick="closeWebSocket()">Close connection</button>
    <div id="message">
    </div>
</body>
<script type="text/javascript">
    var websocket = null;
    var clientId = "wxx-" + Math.random().toString(36).substr(2);

    //Determine whether the current browser supports WebSocket
    if('WebSocket' in window){<!-- -->
        //Connect to WebSocket node
        websocket = new WebSocket("ws://localhost:8080/ws/" + clientId);
    }
    else{<!-- -->
        alert('Not support websocket')
    }

    //Callback method for connection errors
    websocket.onerror = function(){<!-- -->
        setMessageInnerHTML("error");
    };

    //Callback method for successful connection establishment
    websocket.onopen = function(){<!-- -->
        setMessageInnerHTML("Connection successful");
    }

    //Callback method for receiving message
    websocket.onmessage = function(event){<!-- -->
        setMessageInnerHTML(event.data);
    }

    //Callback method for connection closing
    websocket.onclose = function(){<!-- -->
        setMessageInnerHTML("close");
    }

    //Listen to the window closing event. When the window is closed, actively close the websocket connection to prevent the window from closing before the connection is disconnected. The server will throw an exception.
    window.onbeforeunload = function(){<!-- -->
        websocket.close();
    }

    //Display the message on the web page
    function setMessageInnerHTML(innerHTML){<!-- -->
        document.getElementById('message').innerHTML + = innerHTML + '<br/>';
    }

    //Send a message
    function send(){<!-- -->
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
\t
//Close the connection
    function closeWebSocket() {<!-- -->
        websocket.close();
    }
</script>
</html>

maven coordinates

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

WebSocketServer

/**
 * WebSocket service
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {<!-- -->

    private static String mess = "";

    //Storage session object
    private static Map<String, Session> sessionMap = new HashMap();

    /**
     * Method called when the connection is established successfully
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) throws IOException {<!-- -->
        System.out.println("Client:" + sid + "Establish connection");

        String s = sid + "Join group chat<br/>";
        mess + = s;
        sendToAllClient(sid + "Join group chat");
        sessionMap.put(sid, session);
        session.getBasicRemote().sendText(mess);
    }

    /**
     * Method called after receiving client message
     *
     * @param message message sent by the client
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {<!-- -->
        System.out.println("Received information from client:" + sid + ":" + message);
        String s = sid + ":" + message + "<br />";
        mess + = s;
        sendToAllClient(sid + ":" + message);
    }

    /**
     * Method called when the connection is closed
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {<!-- -->
        System.out.println("Connection disconnected:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * Bulk sending
     *
     * @param message
     */
    public void sendToAllClient(String message) {<!-- -->
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {<!-- -->
            try {<!-- -->
                //The server sends a message to the client
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {<!-- -->
                e.printStackTrace();
            }
        }
    }
}

WebSocketConfiguration

/**
 * WebSocket configuration class, used to register WebSocket beans
 */
@Configuration
public class WebSocketConfiguration {<!-- -->

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {<!-- -->
        return new ServerEndpointExporter();
    }

}

WebSocketTask

@Component
public class WebSocketTask {<!-- -->
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * Send messages to the client every 5 seconds via WebSocket
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMessageToClient() {<!-- -->
        webSocketServer.sendToAllClient("This is the message from the server:" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
    }
}

Request address

The server sends a message to the client

The client sends a message to the server