Spring Websocket - How can I detect client disconnect

Eli picture Eli · Dec 13, 2016 · Viewed 15.6k times · Source

I am new to spring

I have this class :

public class Server extends TextWebSocketHandler implements WebSocketHandler {

    WebSocketSession clientsession;
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {

        clientsession = session;

    }

I need to detect a client disconnect on clientsession. implement ApplicationListener but its not clear how I can register the listener? do I need to do it in my web.xml ?

Answer

mattm picture mattm · Dec 15, 2016

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.