Standard Library

Networking

Networking code exchanges bytes across explicit protocol boundaries.

socketpair() returns two connected endpoints. sendall writes encoded bytes into one end, and recv reads up to 16 bytes off the other. The byte boundary is the whole point: "ping".encode("utf-8") produces b'ping', which is what the socket actually moves. (This fragment runs in standard Python only — the Python By Example runner does not expose arbitrary sockets and disables outbound access for edited examples.)

Standard Python

left, right = socket.socketpair()
left.sendall("ping".encode("utf-8"))
data = right.recv(16)
STR"ping"encodeBYTESb'ping'SOCKETBYTESb'ping'decodeSTR"ping"
Text crosses the socket as bytes — `encode` marks the python → wire boundary, `decode` brings the bytes back to a Python `str`.

The complete version adds two things: a try/finally so both endpoints close even if recv or the surrounding work raises, and a second print that decodes the received bytes back into a Python str for display. The first print shows the raw bytes b'ping'; the second shows the decoded text ping.

Source

import socket

left, right = socket.socketpair()
try:
    message = "ping"
    left.sendall(message.encode("utf-8"))
    data = right.recv(16)
    print(data)
    print(data.decode("utf-8"))
finally:
    left.close()
    right.close()

Output

b'ping'
ping

Notes

See also

Run the complete example

Example code

Expected output

b'ping'
ping

Execution time appears here after you run the example.