Standard Library
Networking
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'
pingNotes
- Network protocols move bytes, not Python
strobjects. - Close real sockets when finished, usually with a context manager or
finallyblock. - Use high-level HTTP libraries for application HTTP unless socket-level control is the lesson.
- The verified output came from a real
socketpair()under standard CPython at build time; the in-browser sandbox cannot open sockets, so live runs of this page fail there.
See also
- prerequisite: Bytes and Bytearray
- related: Subprocesses
- next depth: Async Await
Run the complete example
Expected output
b'ping'
ping
Execution time appears here after you run the example.