HttpUrlConnection如何设置SO_KEEPALIVE [英] HttpUrlConnection how to set SO_KEEPALIVE

查看:521
本文介绍了HttpUrlConnection如何设置SO_KEEPALIVE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为JDK stdlib HttpUrlConnection 设置套接字级别选项(如SO_KEEPALIVE)?我正在试图找出一种方法来获取HTTP请求,这些方法不会成为偶尔挂起连接的牺牲品(这似乎是因为网络数据包丢失而经常发生)。更强大的HTTP客户端。我知道有 setReadTimeout 方法,但我试图找到一些东西来推动TCP流回到生活中,而不仅仅是中止它,因为读取超时似乎。或者至少报告连接失败已经发生,而不是永远挂在读取上。但这也允许读取只要它想要假设连接仍处于活动状态。



经过一些检查,似乎SO_KEEPALIVE的默认值是对于C层和Java级别的套接字来说都是关闭。

解决方案

这是基于三个谬误而建立的。


  1. SO_KEEPALIVE不会将TCP流重新回到生活中,尽管其名称选择不当。在默认的两个小时间隔后,它只检测死连接。它不是您要找的。


  2. 读取超时不会中止连接。它会抛出 SocketTimeoutException 。连接仍然存在,后续读取可能会成功。


  3. 检测到丢弃的数据包并在TCP中重新传输。


使用读取超时。


Is there any way to set socket level options (like SO_KEEPALIVE) for a JDK stdlib HttpUrlConnection? I'm trying to figure out a way to GET HTTP requests that doesn't fall victim to occasional "hanging" connections (which seem to occur because of network packet loss every so often). A more robust HTTP client. I know there is the setReadTimeout method but I am trying to find something to nudge the TCP stream back into life, instead of just aborting it, as the read timeout seems to. Or at least report that the connection failure has occurred instead of hanging forever on a read. But that also allows the read to come back "whenever it wants to" assuming the connection is "still active."

With some examination it appears that the default for SO_KEEPALIVE is "off" for both the C layer and Java level sockets.

解决方案

This is founded on not one but three fallacies.

  1. SO_KEEPALIVE doesn't 'nudge the TCP stream back into life', despite its poorly chosen name. It just detects dead connections, after a default interval of two hours. It isn't what you're looking for.

  2. A read timeout doesn't abort the connection. It throws a SocketTimeoutException. The connection is still alive, and a subsequent read may succeed.

  3. Dropped packets are detected and retransmitted in TCP.

Use a read timeout.

这篇关于HttpUrlConnection如何设置SO_KEEPALIVE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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