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

Cap*_*vil 6 java spring websocket spring-websocket spring-webflux

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

对于如何处理客户端断开连接有什么建议吗?

Nic*_*las 6

我在反应式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();
}
Run Code Online (Sandbox Code Playgroud)

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

doFinally但由于某种原因,netty 通道关闭和回调执行之间存在 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]
Run Code Online (Sandbox Code Playgroud)

更新:2017 年 10 月 13 日:

从 Spring 5 GA 开始,上述延迟不存在,并且我观察到我的回调在客户端关闭后立即被调用。不确定这个问题在哪个版本中得到了修复,但正如我所说,它在 5.0 GA 中得到了修复。