基于 JVM 的 longpoll/comet 客户端:路由器杀死空闲连接
我目前有一个基于 JVM 的网络客户端,它使用标准 java.net.HttpURLConnection 执行 HTTP 长轮询(又名 comet)请求。我将连接超时设置得很高(1 小时)。对于大多数用户来说,它工作得很好。但有些用户没有收到服务器发送的数据,最终在1小时后超时。
我的理论是,(NAT)路由器超时并丢弃它们的连接,因为它们在服务器发送任何数据之前空闲太久。
我的问题是:
我可以为 java.net.HttpURLConnection 使用的连接启用 TCP keep-alive 吗?我找不到办法做到这一点。
我应该使用不同的 API(与 HttpURLConnection 不同)吗?
其他解决方案?
I currently have a JVM-based network client that does an HTTP long poll (aka comet) request using the standard java.net.HttpURLConnection. I have timeout set very high for the connection (1 hour). For most users it works fine. But some users do not receive the data sent from the server and eventually time out after 1 hour.
My theory is that a (NAT) router is timing out and discarding their connections because they are idle too long before the server sends any data.
My questions then are:
Can I enable TCP keep-alive for the connections used by java.net.HttpURLConnection? I could not find a way to do this.
Is there a different API (than HttpURLConnection) I should be using instead?
Other solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
java.net.HttpURLConnection
处理Keep-Alive
标头 透明,可控制,默认开启。但您的问题不在于“Keep-Alive”,这是一个更高级别的标志,指示服务器应在处理第一个请求后关闭连接,而不是等待下一个请求。在您的情况下,OSI 堆栈较低级别上的某些内容可能会中断连接。因为长时间保持打开但空闲的 TCP 连接从来都不是一个好的选择(具有两个打开连接的 FTP 协议:一个用于命令,一个用于数据也有同样的问题),所以我宁愿实现某种断开连接/在客户端重试故障安全过程。
事实上,安全限制可能只是几分钟,而不是几小时。只需每隔 60 秒或 5 分钟主动断开与 HTTP 服务器的连接即可。应该做到这一点。
java.net.HttpURLConnection
handlesKeep-Alive
header transparently, it can be controlled and it is on by default. But your problem is not inKeep-Alive
, which is a higher level flag indicating that the server should close the connection after handling the first request but rather waiting for the next one.In your case probably something on the lower level of OSI stack interrupts the connection. Because keeping an open but idle TCP connection for such a long period of time is never a good choice (FTP protocol with two open connections: one for commands and one for data has the same problem), I would rather implement some sort of disconnect/retry fail-safe procedure on the client side.
In fact safe limit would probably be just few minutes, not hours. Simply disconnect from the HTTP server pro-actively every 60 seconds or 5 minutes. Should do the trick.
似乎没有办法为 HttpURLConnection 打开 TCP 保持活动状态。
当版本 4.2 推出并提供 TCP keep-alive 支持时,Apache HttpComponents 将成为一个选项。
There does not appear to be a way to turn on TCP keep-alive for HttpURLConnection.
Apache HttpComponents will be an option when version 4.2 comes out with TCP keep-alive support.