java 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 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 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中修复.来源:https://www.icode9.com/content-1-555901.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值