套接字编程java - 套接字连接存活多长时间?我该如何控制它?

发布于 2024-12-12 21:15:55 字数 460 浏览 3 评论 0原文

您知道如果我不在套接字上执行任何操作,如何保持套接字连接处于活动状态吗? 我只是注意到,如果我的连接在后台并且我不操作它,我会得到以下信息:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

魄砕の薆 2024-12-19 21:15:55

这个问题没有通用的解决方案。远程服务器/服务很可能已决定重置/关闭 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.

翻身的咸鱼 2024-12-19 21:15:55

连接被对等方重置:套接字写入错误

这通常是由于写入已被对等方关闭的连接而引起的。这是应用程序协议错误。在担心连接生命周期之前,您应该首先调查这一点。

Connection reset by peer: socket write error

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文