本文介绍了如果没有数据发送,TCP 套接字会在一段时间后自动关闭吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端服务器的情况,客户端打开一个到服务器的 TCP 套接字,有时很长一段时间会过去,它们之间没有数据发送.我遇到了服务器尝试向客户端发送数据的问题,它似乎成功了,但客户端始终没有收到它,几分钟后,客户端似乎断开了连接.

I have a client server situation where the client opens a TCP socket to the server, and sometimes long periods of time will pass with no data being sent between them. I have encountered an issue where the server tries to send data to the client, and it seems to be successful, but the client never receives it, and after a few minutes, it looks like the client then gets disconnected.

我是否需要每隔一段时间发送某种保活数据包?

Do I need to send some kind of keep alive packet every once in a while?

编辑:请注意,这是在同一台计算机上的同级.该计算机位于 NAT 之后,该 NAT 转发用于该计算机的一系列端口.与服务器连接的客户端通过 DNS 打开连接.即它使用 mydomain.net &连接端口.

Edit: To note, this is with peers on the same computer. The computer is behind a NAT, that forwards a range of ports used to this computer. The client that connects with the server opens the connection via DNS. i.e. it uses the mydomain.net & port to connect.

推荐答案

在 Windows 上,未发送数据的套接字是许多应用程序中的一大麻烦来源,必须正确处理.

On Windows, sockets with no data sent are a big source for trouble in many applications and must be handled correctly.

问题是,可以在系统范围内设置 SO_KEEPALIVE 的时间段(否则,默认值是两小时没用的)或使用后来的 winsock API.

The problem is, that SO_KEEPALIVE's period can be set system-wide (otherwise, a default is useless two hours) or with the later winsock API.

因此,很多应用偶尔会偶尔发送一些字节的数据(被peer忽略)只是为了让网络层在没有收到ACK后宣布断开连接(毕竟该层已经完成了应有的重传和ack超时).

Therefore, many applications do send some occasional byte of data every now and then (to be disregarded by the peer) only to make the network layer declare disconnection after ACK is not received (after all due retransmissions done by the layer and ack timeout).

回答您的问题:不,插座不会自动断开连接.

Answering your question: no, the sockets do not disconnect automatically.

但是,您必须小心上述问题.更复杂的是,测试这种行为非常困难.例如,如果您正确设置了所有内容并希望正确检测断开连接,则无法通过断开物理层来测试它.这是因为 NIC 将感知载波丢失,并且套接字层将发出信号以关闭所有依赖它的应用程序套接字.测试它的一个好方法是将两台计算机连接到 3 条腿和中间的两个开关,断开中间腿,从而防止载波丢失,但仍会物理断开机器.

Yet, you must be careful with the above issue. What complicates it further is that testing this behavior is very hard. For example, if you set everything correctly and you expect to detect disconnection properly, you cannot test it by disconnecting the physical layer. This is because the NIC will sense the carrier loss and the socket layer will signal to close all application sockets that relied on it. A good way to test it is connect two computers with 3 legs and two switches in between, disconnecting the middle leg, thus preventing carrier loss but still physically disconnecting the machines.

这篇关于如果没有数据发送,TCP 套接字会在一段时间后自动关闭吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 07:15