socket.shutdown与socket.clos

2024-10-01 17:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近看到了一些类似这样的代码(sock当然是socket对象):

sock.shutdown(socket.SHUT_RDWR)
sock.close()

对套接字调用shutdown然后关闭它的目的到底是什么?如果有区别,这个套接字将用于非阻塞IO。


Tags: 对象代码io目的closesocketsock区别
3条回答

这里有一个explanation

Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.

调用closeshutdown对底层套接字有两种不同的影响。

首先要指出的是,套接字是底层操作系统中的一个资源,多个进程可以拥有同一底层套接字的句柄。

当您调用close时,它会将句柄计数递减一,如果句柄计数已达到零,则套接字和相关连接将通过正常的关闭过程(有效地向对等方发送FIN/EOF)并释放套接字。

这里需要注意的是,如果由于另一个进程仍然有一个套接字句柄,因此句柄计数未达到零,则连接不会关闭,套接字也不会被释放。

另一方面,调用shutdown进行读写将关闭底层连接并向对等方发送FIN/EOF,而不管有多少进程对套接字有句柄。但是,它不会释放套接字,您仍然需要在之后调用close。

关机关闭说明:Graceful shutdown (msdn)

关机(在您的情况下)表示连接的另一端不再打算读取或写入套接字。然后close释放与套接字相关联的任何内存。

省略shutdown可能会导致套接字在OSs堆栈中逗留,直到连接正常关闭为止。

IMO的“shutdown”和“close”这两个名称具有误导性,“close”和“destroy”将强调它们的区别。

相关问题 更多 >

    热门问题