refer to :
https://www.cnblogs.com/web-learn/p/15148141.html
SpringBoot uses WebSocket_springboot websocket_Looking at the Milky Way Blog-CSDN Blog
java
WebSocketConfig
import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; import javax.servlet.ServletContext; import javax.servlet.ServletException; /** * @author: xxt * @date: 2022/5/23 16:22 * @Description: Enable WebSocket support */ @Configuration public class WebSocketConfig implements ServletContextInitializer { /** * The registration of this bean is used to scan the annotation with @ServerEndpoint to become websocket. If you use an external tomcat, you don't need this configuration file */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } @Override public void onStartup(ServletContext servletContext) throws ServletException { } }
WebSocketServer
import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; /** * @author: xxt * @date: 2022/5/23 16:27 * @Description: WebSocket operation class */ @ServerEndpoint("/websocket/{userId}") @Component @Slf4j public class WebSocketServer { // A connection session with a client, which needs to be used to send data to the client private Session session; // session collection, store the corresponding session private static ConcurrentHashMap<Integer, Session> sessionPool = new ConcurrentHashMap<>(); // The thread-safe Set of the concurrent package is used to store the WebSocket object corresponding to each client. private static CopyOnWriteArraySet<WebSocketSever> webSocketSet = new CopyOnWriteArraySet<>(); /** * Establish a WebSocket connection * * @param session * @param userId user ID */ @OnOpen public void onOpen(Session session, @PathParam(value = "userId") Integer userId) { log.info("WebSocket is establishing a connection, connecting user ID: {}", userId); try { Session historySession = sessionPool. get(userId); // historySession is not empty, indicating that someone has logged into the account, and the logged-in WebSocket object should be deleted if (historySession != null) { webSocketSet. remove(historySession); historySession. close(); } } catch (IOException e) { log.error("Duplicate login exception, error message:" + e.getMessage(), e); } // establish connection this.session = session; webSocketSet. add(this); sessionPool. put(userId, session); log.info("The connection is established, the current online number is: {}", webSocketSet.size()); } /** * An error occurred * * @param throwable e */ @OnError public void onError(Throwable throwable) { throwable. printStackTrace(); } /** * Connection closed */ @OnClose public void onClose() { webSocketSet. remove(this); log.info("The connection is disconnected, the current online number is: {}", webSocketSet.size()); } /** * Receive client messages * * @param message received message */ @OnMessage public void onMessage(String message) { log.info("Received a message from the client: {}", message); } /** * Push messages to specified users * * @param userId user ID * @param message the sent message */ public static void sendMessageByUser(Integer userId, String message) { log.info("User ID: " + userId + ", push content: " + message); Session session = sessionPool. get(userId); try { session.getBasicRemote().sendText(message); } catch (IOException e) { log.error("There was an error in pushing the message to the specified user:" + e.getMessage(), e); } } /** * Group message * * @param message the sent message */ public static void sendAllMessage(String message) { log.info("Send message: {}", message); for (WebSocketSever webSocket : webSocketSet) { try { webSocket.session.getBasicRemote().sendText(message); } catch (IOException e) { log.error("An error occurred in mass sending message:" + e.getMessage(), e); } } } }
html5
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>hangge.com</title> <style> </style> <script type="text/javascript"> // used to fill in the input box for sending messages var messageBox; // div container for displaying messages var messageLog; //WebSocket object var socket; //page loaded window.onload = function() { messageBox = document.getElementById('messageBox'); messageLog = document.getElementById('messageLog'); } //Create a socket object and bind all events function connect() { //Create socket object socket = new WebSocket("ws://localhost:8080/websocket/1"); //Listen to all Web socket events socket.onopen = connectionOpen; socket.onmessage = messageReceived; socket.onerror = errorOccurred; socket.onclose = connectionClosed; } // Disconnect button click function disconnect(){ socket. close(); } //Send message button click function sendMessage(){ // get the data to send var message = messageBox. value; //Send message through socket socket. send(message); // tell the user what just happened messageLog.innerHTML + = "<br>Send: " + message; } //Connection established event response function connectionOpen(e) { messageLog.innerHTML + = "<br>--- Socket connection successful ---"; } //Message received event response function messageReceived(e){ messageLog.innerHTML + = "<br>Received: " + e.data; } // error event response function errorOccurred(e){ messageLog.innerHTML + = "<br>An error occurred: " + e.data; } //connection close event response function connectionClosed(e) { messageLog.innerHTML + = "<br>--- Socket connection closed ---"; } </script> </head> <body> <input id="messageBox" type="text" style="width: 400px;" /><br /><br /> <button onclick="connect()">Connect</button> <button onclick="sendMessage()">send</button> <button onclick="disconnect()">Disconnect</button> <div id="messageLog"></div> </body> </html>