我需要`ping`连接的websocket连接吗? [英] Do I need to `ping` connected websocket connections?

查看:38
本文介绍了我需要`ping`连接的websocket连接吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让 Websocket 连接在不确定的时间内保持活动状态.理想情况下,套接字将每隔一段时间发送一次数据,但这并不能保证,而且我也不想做出假设,因为用户可能处于空闲状态.

I would like to keep the Websocket connection alive for an undefined amount of time. The socket will ideally be sending data every so often but this is not assured, and I also would not like to make assumptions since a user can be in an idle state.

我有一个存储对所有 websocket 连接的引用的对象.我每 x 分钟安排一次功能是否合适?秒?基本上遍历所有连接,ping它们然后丢弃那些没有收到pong的?或者我是否需要启用自动保持连接活动的标志?

I have an object that stores references to all websocket connections. Would it be appropriate for me to schedule a function every x number of minutes? seconds? that basically iterates through all the connections, pings them and then discards those that haven't received pongs? Or do I need to enable a flag that automatically keeps the connection alive?

我在我的服务器上使用 ws 库,但在客户端本地创建 websocket 连接.

I am using the ws library on my server, but create websocket connections natively on the client.

推荐答案

在客户端,没有什么好方法可以让您知道发生了多少代理、防火墙、NAT 等在从客户端计算机到目标服务器的网络路径中.其中任何一个都可以有自己单独的空闲计时器.使用 TCP keepalive 可能工作,但用于从您的客户端到下一跃点的 TCP 会话——这实际上可能是也可能不是最终服务器.

There's no good way for you, on the client end of things, to know how many proxies, firewalls, NATs, etc occur in the network path from your client machine to the destination server. Any one of those could have its own separate idle timer. Using TCP keepalive may work, but only for the TCP session from your client to the next hop -- which may or may not actually be the end server.

鉴于上述情况,我建议,您应该定期 ping 连接的 WebSocket 会话.从通过该(可能是复杂的)网络中间件链保持连接活跃的角度来看,您是否从服务器收到 pong 是无关紧要的;你只是想确保路径上的所有东西都能看到一些流量,以便重置它们的空闲计时器.

Given the above, I would recommend that yes, you should ping your connected WebSocket sessions periodically. Whether you receive the pong from the server is, from the point of view of keeping your connections alive through that (possibly convoluted) chain of network middleboxes, irrelevant; you simply want to make sure that everything along the path sees some traffic flowing in order to reset their idle timers.

显然,您想权衡 ping 连接的 WebSocket 会话的频率与产生的开销;例如,每 1 秒 ping 一次就会有点多.您可能需要进行一些微调,以通过实验确定适合您需要的 ping 间隔时间.

Obviously you want to trade off how often you ping your connected WebSocket sessions with how much overhead is incurred; pinging every 1 second would be a bit much, for example. You may need some fine-tuning to determine, experimentally, just what a good ping interval is for your needs.

希望这会有所帮助!

这篇关于我需要`ping`连接的websocket连接吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆