如何从服务器优雅地关闭套接字
在服务器端,我试图优雅地关闭连接的套接字。我知道套接字上事件的正确顺序应该是:
使用 SocketShutdown.Send 选项关闭套接字
循环/等待,直到套接字接收返回 0 字节
socket Close
我有几个问题:
如果 Socket.Receive 永远不会返回(带有 0 个字节)怎么办字节)?我们会一直试图关闭套接字吗?
每当我在服务器上调用 Close 时,客户端总是会收到“现有连接被远程主机强制关闭”异常。我如何让客户端“优雅地”通知此关闭?
在服务器上,如果我使用异步 Begin/EndReceive 调用,则每当我在套接字上调用 Close 时,它总是会在 Begin/EndReceive 线程上导致 ObjectDisposeException。有没有办法在不发生此异常的情况下关闭套接字?
On the server side, I'm trying to gracefully close a connected socket. I know the proper sequence of events on the Socket should be:
socket Shutdown with the SocketShutdown.Send option
loop/wait until a socket Receive returns with 0 bytes
socket Close
I have a few questions:
what if Socket.Receive never returns (with 0 bytes)? will we be stuck trying to close the socket forever?
whenever i call Close on the server, the Client always receives "an existing connection was forcibly closed by a remote host" exception on their end. how can i have the client notified of this close "gracefully"?
on the server, if I'm using Async Begin/EndReceive calls, whenever I call Close on the socket, it ALWAYS results in an ObjectDisposedException on the Begin/EndReceive thread. Is there no way to Close a socket without this exception from occurring?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
TCP 协议保证套接字最终将关闭,除非对等方拒绝允许它关闭。在这种情况下,您应该永远等待或放弃,无论什么都合适。
如果在接收返回零后关闭套接字,则不会发生这种情况。如果是,您的代码可能做错了什么。
当异步操作正在或可能正在使用资源时,您无法释放该资源。不要调用 close,而是调用 shutdown。在 100% 完成资源使用之前,请勿调用 close。
The TCP protocol guarantees the socket will close eventually unless the peer refuses to allow it to close. In which case, you should wait forever or give up, whatever's appropriate.
If you close the socket after receive returns zero, that should not happen. If it is, your code is likely doing something wrong.
You can't release a resource while an asynchronous operation is or might be using it. Rather than calling close, call shutdown. Don't call close until you're 100% finished with the resource.