Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Websocket - How can I detect client disconnect

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 ?

like image 848
Eli Avatar asked Dec 13 '16 18:12

Eli


People also ask

How do I know if a WebSocket is disconnected?

You can check if a WebSocket is disconnected by doing either of the following: Specifying a function to the WebSocket. onclose event handler property, or; Using addEventListener to listen to the close event.

What causes WebSocket disconnect?

By default, if a ping has not been received in 60 seconds, and the connection has been otherwise inactive, the platform will close the WebSocket. This timeout is configurable in the WS Communication Subsystem configuration, Idle Connection Timeout (sec) parameter.


1 Answers

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.

like image 79
mattm Avatar answered Oct 05 '22 08:10

mattm