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. (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)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'
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.
- Cloudflare Workers support HTTP-style networking through platform APIs; this example avoids outbound calls so the editable lesson stays deterministic and safe.
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.