套接字在远程计算机关闭后保持连接

Socket remains connected after the remote computer closes it

我已经搜索过但没有解决我的问题。 我在本地主机上模拟 TCP 网络。服务器侦听端口,客户端连接到服务器。问题是,当我通过客户端关闭套接字时,Socket.Connected 在服务器中仍然为真。我需要知道客户端何时断开连接。

我想当我在客户端应用程序上调用 Socket.Close 时,一个 TCP FIN 数据包被发送到服务器,对吧?但是好像没有。

你能给我一个解决方案吗?

P.S。关闭前我已经调用了shutdown,但是问题依旧

虽然我没有使用 C# 进行套接字编程的实际经验,但似乎 Socket.Close() 不会发送未决数据,并且暗示不会发送 FIN 数据包。 (在我看来,这有点误导,因为 Close 语义似乎与 Stream.Close() 不同,后者调用 Dispose(true),如果可能的话会尝试刷新。如果我错了,请纠正我。)

MSDN documentation 状态:

For connection-oriented protocols, it is recommended that you call Shutdown before calling the Close method. This ensures that all data is sent and received on the connected socket before it is closed.

If you need to call Close without first calling Shutdown, you can ensure that data queued for outgoing transmission will be sent by setting the DontLingerSocket option to false and specifying a non-zero time-out interval. Close will then block until this data is sent or until the specified time-out expires. If you set DontLinger to false and specify a zero time-out interval, Close releases the connection and automatically discards outgoing queued data.

没有基于通知的方式来了解客户端是否断开连接。这就是 tcp/ip 交流的本质。知道客户端是否连接的通常方法是将数据写入客户端连接。如果报错,可以猜测是客户端断开了。您可以通过查找特定异常来简化启发式方法