Python Glossary Русский

all Python 3socketterm

socket.socket

creating sockets

The socket class: an endpoint of a network connection, TCP (SOCK_STREAM) or UDP (SOCK_DGRAM), over IPv4 or IPv6.

Syntax

s = socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

TCP is a byte stream, not a sequence of messages: one send may arrive as several recv calls and two sends as one, so read in a loop until b'' (the peer closed) or until a known length. send() may transmit only part of the data and returns the byte count; sendall() sends the whole message. Only bytes go over the wire, so encode strings first. settimeout(None) restores blocking mode with no limit, settimeout(0) makes it non-blocking; close sockets with a with block. The module-level socket.dup is an internal name; the sock.dup() method gives you a copy of a socket.

Examples

import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
    srv.bind(('127.0.0.1', 0))  # порт 0: свободный порт выберет система
    srv.listen()
    with socket.create_connection(srv.getsockname(), timeout=2) as cli:
        conn, addr = srv.accept()
        with conn:
            cli.sendall(b'hello ')
            cli.sendall(b'world')
            cli.shutdown(socket.SHUT_WR)
            chunks = []
            while chunk := conn.recv(4):
                chunks.append(chunk)
print(b''.join(chunks))  # → b'hello world'
print(len(chunks) > 1)  # → True — сообщение пришло кусками
import socket
a, b = socket.socketpair()
with a, b:
    try:
        a.sendall('привет')
    except TypeError as e:
        print(e)  # → a bytes-like object is required, not 'str'
    a.sendall('привет'.encode('utf-8'))
    print(b.recv(1024).decode('utf-8'))  # → привет

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy