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

How to Gracefully Close a Socket from the Server(如何从服务器优雅地关闭套接字)

本文介绍了如何从服务器优雅地关闭套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. 使用 SocketShutdown.Send 选项关闭套接字

  1. socket Shutdown with the SocketShutdown.Send option

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

loop/wait until a socket Receive returns with 0 bytes

套接字关闭

我有几个问题:

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

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

每当我在服务器上调用 Close 时,客户端总是会收到现有连接被远程主机强制关闭"异常.我怎样才能优雅地"通知客户此关闭?

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

在服务器上,如果我使用 Async Begin/EndReceive 调用,每当我在套接字上调用 Close 时,它​​总是会在 Begin/EndReceive 线程上导致 ObjectDisposedException.如果不发生这种异常,是否没有办法关闭套接字?

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?

推荐答案

  1. TCP 协议保证套接字最终会关闭,除非对方拒绝允许它关闭.在这种情况下,你应该永远等待或放弃,不管是什么合适的.

  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.

如果在接收返回零后关闭套接字,则不应该发生这种情况.如果是这样,您的代码可能有问题.

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

当异步操作正在或可能正在使用资源时,您不能释放资源.与其调用close,不如调用shutdown.在资源 100% 完成之前,请勿调用 close.

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.

这篇关于如何从服务器优雅地关闭套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何从服务器优雅地关闭套接字

基础教程推荐