Ordering system - Message 02 - websocket message push

Posted by ttroy on Sun, 14 Jun 2020 10:02:44 +0200

1, What is WebSocket

WebSocket: communication between client and server

WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete one handshake, and they can directly create a persistent connection and carry out two-way data transmission.

Now, in order to implement push technology, many websites use Ajax polling technology. Polling is a specific time interval (such as every 1 second), the browser sends HTTP request to the server, and then the server returns the latest data to the browser of the client. This traditional mode brings obvious disadvantages, that is, the browser needs to send requests to the server constantly, but HTTP requests may contain a long header, in which the real effective data may only be a small part, obviously this will waste a lot of bandwidth and other resources.
The WebSocket protocol defined by HTML5 can save server resources and bandwidth, and can communicate in real time.

2, WebSocket implementation

Front end code
stay list.ftl Join in

    var websocket = null;
    //Determine whether the browser supports
    if('WebSocket' in window) {
        websocket = new WebSocket('ws://localhost:8080/sell/webSocket');
    }else {
        alert('This browser does not support websocket!');

    //WebSocket event
    websocket.onopen = function (event) {
        console.log('Establish a connection');

    websocket.onclose = function (event) {
        console.log('Connection closed');

    websocket.onmessage = function (event) {
        console.log('Message received:' + event.data)
        //Pop up reminder (find the front-end code in ibootstrap and copy it to list.ftl Medium)
        // Play music

    websocket.onerror = function () {
        alert('websocket Communication error!');//Popup

    window.onbeforeunload = function () {

Back end code
1. Import dependency


2. Inject serverendpoint exporter (injection environment)

public class WebSocketConfig {
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();

3. Write WebSocket class (under service package, but not service)

public class WebSocket {
    //WebSocket container
    private Session session;

    //The thread safe Set of the concurrent package is used to store the MyWebSocket object corresponding to each client. To realize the communication between the server and the single client, Map can be used for storage, where Key can be the user ID
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

     * Connection established successfully
     * session To connect to a client, you need to send data to the client through it
    public void onOpen(Session session) {
        this.session = session;
        log.info("[websocket Message] has a new connection, total:{}", webSocketSet.size());

     * Close connection
    public void onClose() {
        log.info("[websocket Message] disconnected, total:{}", webSocketSet.size());

     * Client message received
     * message Messages sent by clients
    public void onMessage(String message) {
        log.info("[websocket Message] received the message from the client:{}", message);

     * send message
    public void sendMessage(String message) {
        for (WebSocket webSocket: webSocketSet) {
            log.info("[websocket Message] broadcast message, message={}", message);
            try {
            } catch (Exception e) {

4. Send a message when creating an order

Test: create an order
Front end display:


Console output:

Topics: Session html5 Spring