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. The try/finally closes both endpoints even if recv raises, and the second print decodes the bytes back into a Python str. The in-browser sandbox cannot open sockets, so pressing Run here fails; this output came from a real socket pair under standard CPython at build time.

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
Text crosses the socket as bytes — encode marks the python → wire boundary, decode brings the bytes back to a Python str.

Notes

See also

Run the complete example

Example code

Expected output

b'ping'
ping

Execution time appears here after you run the example.