编程语言
首页 > 编程语言> > java-如何使用Spring 5 Reactive WebSocket检测断开连接的客户端

java-如何使用Spring 5 Reactive WebSocket检测断开连接的客户端

作者:互联网

我设法使用Spring 5 Reactive WebSocket支持(Chapter 23.2.4)创建了一个WebSocketHandler.接收和发送一切正常.但是,我不知道如何检测客户端断开连接.调试客户端断开连接时,它会在HttpServerWSOperations类(netty.http.server包)的服务器端停止,并在其中检测到CloseWebSocketFrame.

任何建议如何处理客户端断开连接?

解决方法:

我在反应式org.springframework.web.reactive.socket.WebSocketHandler中实现了关闭事件处理程序,如下所示:

public Mono<Void> handle(final WebSocketSession session) {
    final String sessionId = session.getId();
    if(sessions.add(sessionId)) {  // add session id to set to keep a count of active sessions
        LOG.info("Starting WebSocket Session [{}]", sessionId);
        // Send the session id back to the client
        WebSocketMessage msg = session.textMessage(String.format("{\"session\":\"%s\"}", sessionId));
        // Register the outbound flux as the source of outbound messages
        final Flux<WebSocketMessage> outFlux = Flux.concat(Flux.just(msg), newMetricFlux.map(metric -> {
            LOG.info("Sending message to client [{}]: {}", sessionId, metric);
            return session.textMessage(metric);             
        }));
        // Subscribe to the inbound message flux
        session.receive().doFinally(sig -> {
            LOG.info("Terminating WebSocket Session (client side) sig: [{}], [{}]", sig.name(), sessionId);
            session.close();
            sessions.remove(sessionId);  // remove the stored session id
        }).subscribe(inMsg -> {
            LOG.info("Received inbound message from client [{}]: {}", sessionId, inMsg.getPayloadAsText());
        });
        return session.send(outFlux);
    }
    return Mono.empty();
}

newMetricFlux字段是出站Websocket消息的来源.挂钩关闭事件的诀窍是入站消息流上的doFinally.当websocket客户端关闭时,入站流量终止.

但是由于某种原因,从关闭网络通道到执行doFinally回调之间有1分钟的延迟.不知道为什么.

这是浏览器客户端连接并立即关闭的日志输出.注意第3行和第4行之间的60秒延迟.

2017-08-03 11:15:41.177 DEBUG 28505 --- [ctor-http-nio-2] r.i.n.http.server.HttpServerOperations   : New http connection, requesting read
2017-08-03 11:15:41.294  INFO 28505 --- [ctor-http-nio-2] c.h.w.ws.NewMetricsWebSocketHandler      : Starting WebSocket Session [87fbe66]
2017-08-03 11:15:48.294 DEBUG 28505 --- [ctor-http-nio-2] r.i.n.http.server.HttpServerOperations   : CloseWebSocketFrame detected. Closing Websocket
2017-08-03 11:16:48.293  INFO 28505 --- [ctor-http-nio-2] c.h.w.ws.NewMetricsWebSocketHandler      : Terminating WebSocket Session (client side) sig: [ON_COMPLETE], [87fbe66]

更新:2017年10月13日:

从Spring 5 GA开始,上述延迟不存在,我观察到在关闭客户端后立即调用了我的回调.不确定此版本已修复,但正如我所说,它已在5.0 GA中修复.

标签:spring-webflux,spring-websocket,websocket,spring,java
来源: https://codeday.me/bug/20191111/2018049.html