Use of WebSocketServer (@ServerEndpoint)

Front-end code

function initWebSocket() {<!-- -->
        if (typeof WebSocket == "undefined") {<!-- -->
          console.log("Your browser does not support WebSocket");
        } else {<!-- -->
          console.log("Your browser supports WebSocket");
          //Implement the WebSocket object, specify the address and port of the server to connect to establish a connection
          //Equivalent to socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
          var wsPathStr = wsPath + uuid;
          console.log("uuid22:" + uuid);
          socket = new WebSocket(wsPathStr);
          //open event
          socket.onopen = function () {<!-- -->
            console.log("Socket is open");
            socket.send("This is a message from the client" + location.href + new Date());
          };

          // get message event
          socket.onmessage = function (msg) {<!-- -->
            // debugger;
            console.log(msg.data);
            var data = JSON. parse(msg. data);
            if (data.code == 200) {<!-- -->
              alert("Successful login!");
              // Store the data you need for your business here. how to let yourself see
              window.sessionStorage.uuid = uuid;
              window.sessionStorage.userId = data.userId;
              window.sessionStorage.projId = data.projId;

              window.location.href = "pages/upload.html";
            } else {<!-- -->
              //If expired, close the connection, reset the connection, refresh the QR code
              // socket. close();
              //initQrImg();
              debugger;
              let path2 = getQrPath2 + "/" + uuid;
              axios
                .get(path2, {<!-- -->
                  params: {<!-- --> dd: "cc" },
                })
                .then(
                  function (success) {<!-- -->
                    console.log("Success");
                  },
                  function (fail) {<!-- -->
                    console.log("failure");
                  }
                )
                .catch(function (error) {<!-- -->
                  console.log("Exception");
                });
            }

            //Found the message to enter and start processing the front-end trigger logic
          };
          //Close event
          socket.onclose = function () {<!-- -->
            console.log("Socket is closed");
          };
          // an error event occurred
          socket.onerror = function () {<!-- -->
            alert("Socket has an error");
            //You can try to refresh the page at this time
          };
        }

Backend Java code

package com.example.poi.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author xu
 * @create 2023/7/21 19
 */
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {<!-- -->
    static Log log = LogFactory. get(WebSocketServer. class);

    //Static variable, used to record the current number of online connections. It should be designed to be thread-safe.
    private static int onlineCount = 0;

    //The thread-safe Set of the concurrent package is used to store the MyWebSocket object corresponding to each client.
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //A connection session with a client needs to be used to send data to the client
    private Session session;

    //Receive sid
    private String sid="";

    /**
     * The method to call when the connection is successfully established
     *
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {<!-- -->
        this.session = session;
        webSocketSet.add(this); //add to set
        addOnlineCount(); //Add 1 to the online count
        log.info("There is a new window to start listening: " + sid + ", the current online number is " + getOnlineCount());
        this.sid=sid;
        /*try {
            sendMessage("connected successfully");
        } catch (IOException e) {
            log.error("websocket IO exception");
        }*/
    }

    /**
     * The method to call when the connection is closed
     */
    @OnClose
    public void onClose() {<!-- -->
        webSocketSet.remove(this); //Remove from set
        subOnlineCount(); //Online count minus 1
        log.info("A connection is closed! The current online number is " + getOnlineCount());
    }

    /**
     * The method called after receiving the client message
     * The message sent by the client
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {<!-- -->
        log.info("Received message from window" + sid + ":" + message);
        //Mass message
        for (WebSocketServer item : webSocketSet) {<!-- -->
            try {<!-- -->
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name","Zhang San");
                jsonObject.put("code",2001);
                jsonObject.put("userId",16);
                jsonObject.put("projId",200);
                item. sendMessage(jsonObject. toString());
            } catch (IOException e) {<!-- -->
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {<!-- -->
        log.error("An error occurred");
        error. printStackTrace();
    }

    /**
     * Realize server active push
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {<!-- -->
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * Send a message
     * @param message
     * @param sid
     * @throws IOException
     */
    public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {<!-- -->
        log.info("Push message to window" + sid + ", push content: " + message);
        for (WebSocketServer item : webSocketSet) {<!-- -->
            try {<!-- -->
                //Here you can set to only push to this sid, if it is null, push all
                if(sid == null) {<!-- -->
                    item. sendMessage(message);
                }else if(item. sid. equals(sid)){<!-- -->
                    item. sendMessage(message);
                }
            } catch (IOException e) {<!-- -->
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {<!-- -->
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {<!-- -->
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {<!-- -->
        WebSocketServer.onlineCount--;
    }


    /**This bean must be available to use webSocketServer*/
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {<!-- -->
        return new ServerEndpointExporter();
    }

}

pom

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>


        <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.13</version>
        </dependency>

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

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.10</version>
        </dependency>

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

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


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

Generate QR code

 //Get the login QR code and put in the Token
    //@CrossOrigin
    @RequestMapping(value = "/getLoginQr", method = RequestMethod.GET)
    public void createCodeImg(HttpServletRequest request, HttpServletResponse response){<!-- -->
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");

        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        try {<!-- -->

            //There is nothing to do here, just generate a UUID and insert it into the database table
            //String uuid = userService.createQrImg();
            String uuid = "jdhasndi452iiwn11";
            response.addHeader("uuid", uuid);
            response.addHeader("Access-Control-Expose-Headers", "uuid");
            response.addHeader("Access-Control-Allow-Origin", "*");
            // Here is the QrCodeUtil in the open source tool class hutool
            // URL: http://hutool.mydoc.io/
            QrCodeUtil.generate(uuid, 300, 300, "jpg", response.getOutputStream());
            System.out.println("**");
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        }
    }

Scan code frontend

<div id="qrImgDiv"></div>
function initQrImg() {<!-- -->
        $("#qrImgDiv").empty();

        var xmlhttp;
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", getQrPath, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {<!-- -->
          console. log(this);
          uuid = this. getResponseHeader("uuid");
          console.log("uuid=", uuid);

          if (this. status == 200) {<!-- -->
            var blob = this. response;
            var img = document. createElement("img");
            img.className = "qrCodeBox-img";
            img.onload = function (e) {<!-- -->
              window.URL.revokeObjectURL(img.src);
            };
            img.src = window.URL.createObjectURL(blob);
            document.getElementById("qrImgDiv").appendChild(img);
          }
        };
        xmlhttp. send();
      }