Jas*_*ker 118 python sockets asynchronous
我最近看到了一些看起来像这样的代码(当然sock是一个套接字对象):
sock.shutdown(socket.SHUT_RDWR)
sock.close()
Run Code Online (Sandbox Code Playgroud)
在套接字上调用shutdown然后关闭它的目的究竟是什么?如果它有所不同,则此套接字用于非阻塞IO.
Rob*_*nes 229
调用close并对shutdown底层套接字有两种不同的效果.
首先要指出的是,套接字是底层操作系统中的资源,多个进程可以拥有相同底层套接字的句柄.
当您调用close它时,句柄计数减1,如果句柄计数达到零,则套接字和关联连接将通过正常关闭过程(有效地向对等方发送FIN/EOF)并释放套接字.
这里需要注意的是,如果句柄计数未达到零,因为另一个进程仍然具有套接字的句柄,则连接未关闭且套接字未被释放.
另一方面,调用shutdown读取和写入会关闭底层连接并向对等方发送FIN/EOF,而不管有多少进程处理套接字.但是,它不会释放套接字,您仍然需要在之后调用close.
断开
Strictly speaking, you’re supposed to use
shutdownon a socket before youcloseit. Theshutdownis an advisory to the socket at the other end. Depending on the argument you pass it, it can mean "I’m not going to send anymore, but I’ll still listen", or "I’m not listening, good riddance!". Most socket libraries, however, are so used to programmers neglecting to use this piece of etiquette that normally acloseis the same asshutdown(); close(). So in most situations, an explicit shutdown is not needed....