【问题标题】:Jetty WebSocket - onWebSocketClose session wantedJetty WebSocket - 需要 onWebSocketClose 会话
【发布时间】:2020-08-05 11:35:16
【问题描述】:

我正在努力在收到 onWebSocketClose 事件时如何找出会话。 官方文档:https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/websocket/api/WebSocketAdapter.html#onWebSocketClose(int,java.lang.String)

上面说有两个参数:onWebSocketClose​(int statusCode, java.lang.String reason)

另一个网站说,有 3 个参数: 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)

目前在 WebSocketOpen 上,我将会话添加到这样的集合中:

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);
}

在 WebSocketClose 上,我想像这样再次删除这个会话:

   @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());
    }

但似乎可选的会话参数不可用,如官方文档中所述,因此将其标记为错误。

知道如何解决吗?提前致谢!

【问题讨论】:

    标签: websocket jetty java-websocket


    【解决方案1】:

    好的,我发现了。在此对象的 WebSocketClose 事件中,有一个方法 getSession() 可用。

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

    【讨论】:

    • 您使用的是哪个版本的 Jetty?我没有那个“this.getSession()”“StatusWebsocket 类型的方法 getSession() 未定义”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2015-08-14
    相关资源
    最近更新 更多