套接字编程java - 套接字连接存活多长时间?我该如何控制它?
您知道如果我不在套接字上执行任何操作,如何保持套接字连接处于活动状态吗? 我只是注意到,如果我的连接在后台并且我不操作它,我会得到以下信息:
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.DataOutputStream.writeInt(Unknown Source)
那么,如何控制连接在一段空闲时间后不会丢失以及默认情况下在多长时间后发生?
Do you know how can I keep alive a socket connection if I do not do any actions on the socket?
I just noticed that if my connection is on background and I do not operate it I get this:
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.DataOutputStream.writeInt(Unknown Source)
So, how can I control that the connection will not be lost after some idle time and after how much time by default does it happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题没有通用的解决方案。远程服务器/服务很可能已决定重置/关闭 TCP/IP 连接。它如何以及为何做出决定取决于应用程序。需要特定于应用程序的解决方案来防止这种情况发生。
FWIW,SO_KEEP_ALIVE 机制导致协议栈偶尔在空闲的 TCP/IP 连接上交换消息。如果您在 NAT 连接上遇到由于端口重用而重置的情况,这可能会有所帮助。相关的Java方法是
Socket.setKeepAlive
。This problem has no general solution. It is quite likely that the remote server / service that has decided to reset/close the TCP/IP connection. How and why it decides is application specific. An application specific solution will be required to prevent it.
FWIW, the SO_KEEP_ALIVE mechanism causes the protocol stack to occasionally exchange messages on an otherwise idle TCP/IP connection. This may help if you are experiencing resets on a NATed connection due to port reuse. The relevant Java method is
Socket.setKeepAlive
.这通常是由于写入已被对等方关闭的连接而引起的。这是应用程序协议错误。在担心连接生命周期之前,您应该首先调查这一点。
This is usually caused by writing to a connection that has already been closed by the peer. It is an application protocol error. You should investigate that first before worrying about connection lifetimes.