如何从服务器优雅地关闭套接字

发布于 2024-12-11 06:19:33 字数 502 浏览 0 评论 0原文

在服务器端,我试图优雅地关闭连接的套接字。我知道套接字上事件的正确顺序应该是:

  1. 使用 SocketShutdown.Send 选项关闭套接字

  2. 循环/等待,直到套接字接收返回 0 字节

  3. socket Close

我有几个问题:

  1. 如果 Socket.Receive 永远不会返回(带有 0 个字节)怎么办字节)?我们会一直试图关闭套接字吗?

  2. 每当我在服务器上调用 Close 时,客户端总是会收到“现有连接被远程主机强制关闭”异常。我如何让客户端“优雅地”通知此关闭?

  3. 在服务器上,如果我使用异步 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:

  1. socket Shutdown with the SocketShutdown.Send option

  2. loop/wait until a socket Receive returns with 0 bytes

  3. socket Close

I have a few questions:

  1. what if Socket.Receive never returns (with 0 bytes)? will we be stuck trying to close the socket forever?

  2. 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"?

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

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

发布评论

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

评论(1

友谊不毕业 2024-12-18 06:19:33
  1. TCP 协议保证套接字最终将关闭,除非对等方拒绝允许它关闭。在这种情况下,您应该永远等待或放弃,无论什么都合适。

  2. 如果在接收返回零后关闭套接字,则不会发生这种情况。如果是,您的代码可能做错了什么。

  3. 当异步操作正在或可能正在使用资源时,您无法释放该资源。不要调用 close,而是调用 shutdown。在 100% 完成资源使用之前,请勿调用 close。

  1. 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.

  2. If you close the socket after receive returns zero, that should not happen. If it is, your code is likely doing something wrong.

  3. 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.

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