Python Glossary Русский

all Python 3socketfunction

socket.socketpair()

creating sockets

Creates a pair of sockets already connected to each other: an in-process channel with no network and no ports.

Syntax

a, b = socket.socketpair(family=AF_UNIX, type=SOCK_STREAM, proto=0)

The easiest way to practise with sockets and to test network code: no server, port or accept() needed. On Unix the pair is AF_UNIX by default, on Windows it is emulated over AF_INET on 127.0.0.1. Both halves must be closed. recv() on an empty socket waits forever, so set settimeout() in tests to get TimeoutError instead of a hang.

Examples

import socket
a, b = socket.socketpair()
with a, b:
    a.sendall(b'ping')
    print(b.recv(1024))  # → b'ping'
    b.settimeout(0.1)
    try:
        b.recv(1024)
    except TimeoutError:
        print('нечего читать')  # → нечего читать
import socket
a, b = socket.socketpair()
print(a.family.name)  # → ? AF_UNIX (AF_INET на Windows)
a.close()
print(b.recv(1024))  # → b'' — другая сторона закрыта
b.close()

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy