how to capture connection event in my webSocket server with Spring 4?

前端 未结 3 529
北海茫月
北海茫月 2021-01-05 19:55

I did a simple web socket communication with spring 4,STOMP and sock.js, following this https://github.com/rstoyanchev/spring-websocket-portfolio and this http://assets.spri

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 20:40

    Spring WebSocket publishes events when messages are received from the client, if you are using STOMP, these are the events published:

    • SessionConnectedEvent
    • SessionConnectEvent
    • SessionDisconnectEvent
    • SessionSubscribeEvent
    • SessionUnsubscribeEvent

    The easiest way to detect connects and disconnects is by implementing an event listener for the mentioned events.

    public class WebSocketEventListener {
    
        @EventListener
        private void handleSessionConnected(SessionConnectEvent event) {
            ...
        }
    
        @EventListener
        private void handleSessionDisconnect(SessionDisconnectEvent event) {
            ...
        }
    }
    

    Here's a sample implementation that keeps track of connected users: https://github.com/salmar/spring-websocket-chat/blob/master/src/main/java/com/sergialmar/wschat/event/PresenceEventListener.java

提交回复
热议问题