且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在客户端和服务器(python)中正确关闭套接字

更新时间:2023-01-18 09:06:20

看起来您正在寻找的是正常关机.首先,您的代码不起作用,因为您在调用 shutdown 后立即关闭了套接字.

It looks like what you are looking for is an graceful shutdown. First your code does not work because you are closing socket immediately after calling shutdown.

规则是,在正常关闭中,双方必须知道关闭并在任何实际关闭套接字之前确认.我只在这个 MSDN 页面,即使它在其他SO 答案中被引用.

The rule is that in a graceful shutdown, both sides must be aware of the shutting down and have acknowledged it before any actually closes the socket. I only found reference for that in this MSDN page, even if it is cited on this other SO answer.

这里是一个简化的演示,如果引用页面更好地解释(我不知道如何在 SO 中正确格式化表格 :-( ) :

Here is a simplified presentation of what is better explained if referenced page (I do not know how to properly format tables in SO :-( ) :

  • 第 1 部分发出 shutdown(socket.SHUT_WR) 通知它要终止连接,并继续从套接字读取
  • 第 2 部分接收套接字上的文件结束指示(空读),并且仍然可以发送任何剩余的数据 - 然后依次调用 shutdown(socket.SHUT_WR)
  • 第 1 部分收到套接字上的文件结尾,并知道其他部分已使用连接终止
  • 然后两个部分都可以关闭套接字
  • part 1 issues shutdown(socket.SHUT_WR) to notify it wants to terminate connexion, and continues to read from socket
  • part 2 receives end of file indication on socket (empty read), and can still send any remaining data - it then calls in turn shutdown(socket.SHUT_WR)
  • part 1 receives end of file on socket and knows that other part has terminated using connection
  • both parts can then close the socket

备注:第 2 部分是否在第 1 部分收到文件结尾之前实际关闭套接字并不重要,因为第 1 部分已经在等待终止的指示:不会丢失任何数据

Remark : it does not matter if part 2 actually closes socket before part 1 received end of file, because part 1 was already only waiting for an indication of termination : no data can have been lost