如果连接仍然打开,Socket.Receive() 可以返回 0 吗?

发布于 2024-10-11 22:02:04 字数 259 浏览 1 评论 0原文

我正在编写一个通过套接字发送和接收数据的 C# .NET 服务器应用程序,如果客户端应用程序在没有以正确方式关闭套接字的情况下崩溃,我会遇到一些问题。

我已将“接收超时”设置为给定值,并且我希望 Socket.Receive() 在该时间后抛出异常。但该方法只是返回 0。

所以我的问题是:如果 Socket.Receive() 返回 0,套接字是否可能仍处于打开状态?或者我可以放心地假设它已关闭吗?

(可能有点难以理解。如果是这样,请在评论中告诉我)

I am writing a C# .NET server application that sends and receives data over Sockets, and I am having some issues if the client application crashes without closing the socket the right way.

I have set the 'receive timeout' to a given value, and I expected the Socket.Receive() to throw an exception after that amount of time. But instead the method just returns 0.

So my question is: Is it possible that the socket is still open if the Socket.Receive() returns 0? Or can I safely assume that it is down?

(Might be a bit tricky to understand. If so, please let me know in the comments)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

尐偏执 2024-10-18 22:02:04

没有。如果收到 0,则表示已关闭。

来自 MSDN:

如果远程主机使用 Shutdown 方法关闭 Socket 连接,并且已接收到所有可用数据,则 Receive 方法将立即完成并返回零字节。

http://msdn.microsoft.com/en-us/library/8s4y8aff.aspx

Nope. It's down if you receive 0.

From MSDN:

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

http://msdn.microsoft.com/en-us/library/8s4y8aff.aspx

邮友 2024-10-18 22:02:04

你的问题有点混乱。 Socket 一直处于打开状态,直到将其关闭。 连接一直打开,直到任一端将其关闭。连接的读取端可以通过发送方关闭连接的输出来关闭。因此,当读取连接时,如果对等方已关闭他的套接字或关闭它的输出,您将收到零。此时,您的套接字仍然打开,尽管您现在应该将其关闭。

如果本地应用程序关闭了输入套接字,它也将返回零。

Your question is a little confused. The Socket is open until you close it. The connection is open until either end closes it. The read side of a connection can be closed by the sender shutting it down for output. So when reading a connection you will receive zero if the peer has either closed his socket or shut it down for output. At that point, your socket is still open, although you should now close it.

It will also return zero if the local application has shutdown the socket for input.

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