websocket used in springboot + vue

1, websocket A springboot Realization

  In java background, WebSocket is configured as a server, which is configured as follows

@Configuration
public class WebSocketConfig {
  
    @Bean(name="serverEndpointExporter")
    public ServerEndpointExporter getServerEndpointExporterBean(){
        return new ServerEndpointExporter();
    }
}

  After adding the above configuration, you can edit your own websocket implementation class, as the following

@Component
@ServerEndpoint(value = "/messageSocket/{userId}")
public class MessageWebSocket {

    private static final Logger logger = LoggerFactory.getLogger(MessageWebSocket.class);

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

    /**
     * key: userId value: sessionIds
     */
    private static ConcurrentHashMap<Integer, ConcurrentLinkedQueue<String>> userSessionMap =  new ConcurrentHashMap<>();

    /**
     * Concurrent package of thread-safe Map, used to store MyWebSocket objects corresponding to each client.
     */
    private static ConcurrentHashMap<String, MessageWebSocket> websocketMap = new ConcurrentHashMap<>();

    /**
     * key: sessionId value: userId
     */
    private static ConcurrentHashMap<String, Integer> sessionUserMap = new ConcurrentHashMap<>();

    /**
     * The current connection session, it is necessary to transmit data to the client
     */
    private Session session;

    /**
     * Connection method for establishing a successful call
     * */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        System.out.println(applicationContext);
        try {
            this.session = session;
            String sessionId = session.getId();
            //建立userId和sessionId的关系
            if(userSessionMap.containsKey(userId)) {
                userSessionMap.get(userId).add(sessionId);
            }else{
                ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
                queue.add(sessionId);
                userSessionMap.put(userId, queue);
            }
            sessionUserMap.put(sessionId, userId);
            // build relationships and sessionId websocket cited 
            IF (! WebsocketMap.containsKey (sessionId)) {
                websocketMap.put(sessionId, this);
                addOnlineCount ();            // Online plus 1 
            }
        }catch (Exception e){
            logger.error ( "connection failed" );
            String es = ExceptionUtils.getFullStackTrace(e);
            logger.error (s);
        }
    }

    /**
     * Close call connection method
     */
    @OnClose
    public void onClose() {
        String sessionId = this.session.getId();
        //移除userId和sessionId的关系
        Integer userId = sessionUserMap.get(sessionId);
        sessionUserMap.remove(sessionId);
        if(userId != null) {
            ConcurrentLinkedQueue<String> sessionIds = userSessionMap.get(userId);
            if(sessionIds != null) {
                sessionIds.remove(sessionId);
                if (sessionIds.size() == 0) {
                    userSessionMap.remove(userId);
                }
            }
        }
        // remove sessionId and websocket relations 
        IF (websocketMap.containsKey (sessionId)) {
            websocketMap.remove(sessionId);
            subOnlineCount ();            // line number minus 1 
        }
    }

    /**
     * Method call after receiving the client message
     *
     * @Param messageStr message sent by the client
     **/
    @OnMessage
    public void onMessage(String messageStr, Session session, @PathParam("userId") Integer userId) throws IOException {
   
    }

    /**
     *
     * @param session
     * @Param error when connecting a callback when an error occurs
      * /
    @OnError
    public void onError(Session session, Throwable error) {
        String es = ExceptionUtils.getFullStackTrace(error);
        logger.error (s);
    }


    /**
     * Initiative to implement server push
     */
    public void sendMessage(String message, Integer toUserId) throws IOException {
        if(toUserId != null && !StringUtil.isEmpty(message.trim())){
            ConcurrentLinkedQueue<String> sessionIds = userSessionMap.get(toUserId);
            if(sessionIds != null) {
                for (String sessionId : sessionIds) {
                    MessageWebSocket socket = websocketMap.get(sessionId);
                    socket.session.getBasicRemote().sendText(message);
                }
            }
        }else{
            logger.error ( "receiving user connection is not found, the user is not connected or disconnected" );
        }
    }

    public void sendMessage(String message, Session session) throws IOException {
        session.getBasicRemote().sendText(message);
    }

     /**
    * Get Online
    */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
     /**
    * Online plus one
    */
    public static synchronized void addOnlineCount() {
        MessageWebSocket.onlineCount++;
    }
    /**
    * Online minus one
    */
    public static synchronized void subOnlineCount() {
        MessageWebSocket.onlineCount--;
    }
}

Work to this end has already done a background service, and how to connect as a client front end of it, please continue to read. .

In order to achieve disconnect automatically reconnect, reconnecting-websocket.js components we use

// WebSocket connection instance 
the let WebSocket = null ;

// initial talk websocket example 
function initWebSocket (the userId, onMessageFunc) {
     @ WS address -> Here is your request path 
    the let Host urlConfig.wsUrl + = 'messageSocket /' + the userId;
     IF ( 'a WebSocket' in window) {
        WebSocket = new new (Host) ReconnectingWebSocket;
         // connection error 
        websocket.onerror = function () {
        }

        // successful connection 
        websocket.onopen = function () {
        }

        // receive callback messages, e.data the information received 
        websocket.onmessage = function (E) {
        }

        // connect callback closed 
        websocket.onclose = function () {
        }
        
        // listening window closing event, when the window is closed, take the initiative to close websocket connected, not disconnected to prevent the connection window is closed, server-side will throw an exception. 
        = window.onbeforeunload function () {
            closeWebSocket();
        }
    } else {
        Alert ( 'current browser does not support the WebSocket' )
         return ;
    }
}

// Close WebSocket connection 
function closeWebSocket () {
    websocket.close();
}

// send message 
function the sendMessage (Message) {
   websocket.send(message);
}

Thus a simple complete websocket has been completed, specific functions can be extended so basic.

 

  

Guess you like

Origin www.cnblogs.com/zxb1996/p/simple_websocket.html