Search code examples
websocketjettyjava-websocket

Jetty WebSocket - onWebSocketClose session wanted


I'm struggling how to find out the session when receiving the onWebSocketClose event. Official docs: https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/websocket/api/WebSocketAdapter.html#onWebSocketClose(int,java.lang.String)

It says there are two parameters: onWebSocketClose​(int statusCode, java.lang.String reason)

Another site says, that there are 3 parameters: https://www.eclipse.org/jetty/documentation/current/jetty-websocket-api-annotations.html

@OnWebSocketClose
An optional method level annotation.

Flags one method in the class as receiving the On Close event.

Method signature must be public, not abstract, and return void.

The method parameters:

Session (optional)
int closeCode (required)
String closeReason (required)

Currently on WebSocketOpen I add the session to a collection like this:

private static Set<Session> connections = Collections.synchronizedSet(new HashSet<Session>());
private static final Logger logger = LogManager.getLogger(WebSocketEvent.class);

@Override
public void onWebSocketConnect(Session session)
{
    super.onWebSocketConnect(session);
    connections.add(session);
    logger.debug("Socket Connected: " + session);
}

And on WebSocketClose I want to delete this session again like this:

   @Override
    public void onWebSocketClose(Session session, int statusCode, String reason)
    {
        super.onWebSocketClose(session,statusCode,reason);
        logger.debug("Connection closed. IP: " + session.getRemoteAddress().getAddress().toString()+ "; rc: "+statusCode+ "; reason: "+ reason);
        connections.remove(session);
        logger.debug("Session with following IP removed from list: " + session.getRemoteAddress().getAddress().toString());
    }

But it seems that the optional session parameter is not available like described in official docs so it marks it as an error.

Any idea how to solve it? Thanks in advance!


Solution

  • Ok I found it out. On WebSocketClose Event in this object there is a method getSession() available.

    @Override
    public void onWebSocketClose(int statusCode, String reason)
    {
        connections.remove(this.getSession());
        super.onWebSocketClose(statusCode,reason);
        logger.debug("Connection closed. rc: "+statusCode+ "; reason: "+ reason);
    }