Spring Websocket - How can I detect client disconnect

The WebSocketHandler afterConnectionClosed function is called after a websocket client disconnects. You simply need to override this in the manner that you override handleTextMessage.

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus){
    // your code here
}

There may be substantial delay between the client disconnect and your server event detection. See details about real-time disconnection detection.


You will need to override configureClientOutboundChannel and configureClientInboundChannel of AbstractWebSocketMessageBrokerConfigurer, providing your interceptor

Another way is using ApplicationEvents.

Both methods are described here: http://www.sergialmar.com/2014/03/detect-websocket-connects-and-disconnects-in-spring-4/

public class StompConnectEvent implements ApplicationListener<SessionConnectEvent> {

private final Log logger = LogFactory.getLog(StompConnectEvent.class);

public void onApplicationEvent(SessionConnectEvent event) {
    StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());

    String  company = sha.getNativeHeader("company").get(0);
    logger.debug("Connect event [sessionId: " + sha.getSessionId() +"; company: "+ company + " ]");
}

}

I hope that help. Let me know if I need to explain more.


You can use listeners to detect when session is connected or closed. More information about listeners you can find by this link.

Example how to detect connected session:

@Component
public class SessionConnectedEventListener implements ApplicationListener<SessionConnectedEvent> {

    private IWebSocketSessionService webSocketSessionService;

    public SessionConnectedEventListener(IWebSocketSessionService webSocketSessionService) {
        this.webSocketSessionService = webSocketSessionService;
    }

    @Override
    public void onApplicationEvent(SessionConnectedEvent event) {
        webSocketSessionService.saveSession(event);
    }
}

Example how to detect when session is disconneted:

@Component
public class SessionDisconnectEventListener implements ApplicationListener<SessionDisconnectEvent> {

    private IWebSocketSessionService webSocketSessionService;

    public SessionDisconnectEventListener(IWebSocketSessionService webSocketSessionService) {
        this.webSocketSessionService = webSocketSessionService;
    }

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        webSocketSessionService.removeSession(event);
    }
}