Spring Websocket - 如何检测客户端断开连接

时间:2016-12-13 18:10:49

标签: spring websocket spring-websocket

我是春天的新手

我有这堂课:

public class Server extends TextWebSocketHandler implements WebSocketHandler {

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

        clientsession = session;

    }

我需要在clientsession上检测客户端断开连接。 实现ApplicationListener,但不清楚我如何注册监听器? 我需要在我的web.xml中执行此操作吗?

3 个答案:

答案 0 :(得分:4)

在websocket客户端断开连接后调用WebSocketHandler afterConnectionClosed函数。您只需要以覆盖handleTextMessage的方式覆盖它。

客户端断开连接和服务器事件检测之间可能存在大量延迟。 See details about real-time disconnection detection

答案 1 :(得分:3)

您需要覆盖AbstractWebSocketMutageBrokerConfigurer的configureClientOutboundChannel和configureClientInboundChannel,提供您的拦截器

另一种方法是使用ApplicationEvents。

这两种方法都在这里描述: 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 + " ]");
}

}

我希望有所帮助。如果我需要解释更多,请告诉我。

答案 2 :(得分:2)

您可以使用侦听器来检测会话何时连接或关闭。 有关您可以通过此link.

找到的听众的更多信息

如何检测连接会话的示例:

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

如何检测会话断开连接的示例:

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