Python Glossary Русский

Python 3.7+socketfunction

socket.close()

file descriptors and ancillary data

Closes a socket given its raw file descriptor: an os.close() equivalent that also works for sockets on Windows.

Syntax

socket.close(fd)

Use it when you hold a number rather than an object: after sock.detach() or a descriptor from other code. On Windows os.close() does not close sockets, hence this function. Never close a descriptor still owned by a socket object: the object will later close the same number, which the OS may already have handed to another file.

Examples

import socket
a, b = socket.socketpair()
fd = a.detach()  # объект больше не владеет дескриптором
print(a.fileno())  # → -1
socket.close(fd)
b.settimeout(1)
print(b.recv(1024))  # → b'' — другая сторона закрыта
b.close()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy