Python Socket Programming Cookbook: TCP & UDP
Zusammenfassung
Pixel shares a beginner-friendly Python 3 socket programming cookbook using only the standard library. It covers TCP and UDP, socket reuse, binary struct packing, byte handling, and protocol fundamentals, with scripts that print connections and state changes so community members can observe networking in action.
DEV Community
Python 3 Standard Library Socket Programming Cookbook: TCP, UDP, select.select(), struct Packing, and Checksums
A zero-dependency cookbook for beginners. Everything below uses only the Python 3 standard library (socket, select, struct, hashlib, zlib, json, sys), flat procedural code, no asyncio, threads, or classes. Every script prints connections, messages and state changes so you can watch the protocol work. Run servers and clients in separate terminal tabs with python3 script.py . Part 1: Core Concepts & Standard Library Rules What a Socket Is: An Operating System endpoint that sends and receives raw bytes over a network. IP vs. Port: The IP address ('localhost' or '127.0.0.1') identifies the machine; the Port (an integer like 10000) identifies the specific Python process. Networks Only Speak Bytes (b"..."): Convert str to bytes before sending with .encode(), and convert received bytes back to str with .decode(). TCP (SOCK_STREAM) vs. UDP (SOCK_DGRAM): TCP is connection-oriented (bind -> listen -> accept on server; connect -> sendall -> recv on client). UDP is connectionless (sendto and recvfrom). A UDP server uses a single socket for all clients and never uses select.select(). Socket Port Reuse (SO_REUSEADDR): Always add server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) before bind() on TCP servers and proxies to avoid Address already in use errors when restarting. Binary Struct Packing (struct.Struct): Format codes: i (4-byte int), I (4-byte unsigned int), f (4-byte float), ? (1-byte bool), c or 1s (1-byte char as bytes), Xs like 7s (X-byte string as bytes). C Alignment Padding Rule: Never count bytes manually ('c i' is 8 bytes due to 3 padding bytes; 'i c' is 5 bytes; 'i i c' is 9 bytes; 'I I 1s' is 12 bytes; '7s6s' is 13 bytes). Always pass packer.size to recv(packer.size). Null-Byte Padding Rule: Packing a shorter string like b"FAIL" into a 7s field pads the trailing bytes with null bytes (b"FAIL\x00\x00\x00"). Always strip null bytes after unpacking: status = status_bytes.decode().strip('\x00'). Part 2: Essential Building Blocks import sys, struct, json, hashlib, zlib
1. Command-Line Arguments (python3 script.py localhost 10000 input.txt)
ip = sys.argv[1]
port = int(sys.argv[2])
filename = sys.argv[3]
2. Struct Packing & Unpacking
packer = struct.Struct('i i 1s')
packed_bytes = packer.pack(10, 25, b'+')
a, b, raw_op = packer.unpack(packed_bytes)
op = raw_op.decode().strip('\x00')
3. Delimiter-Separated Payloads (':', ';', '|')
numbers = [3, 7, 12, 18, 20]
bet = 500
msg_bytes = (":".join(str(x) for x in numbers) + f":{bet}").encode()
parts = [int(x) for x in msg_bytes.decode().split(":")]
recv_nums, recv_bet = parts[:-1], parts[-1]
4. Reading Text, JSON, and Binary Files
with open("input.json", "r") as f:
data = json.load(f)
5. MD5 and CRC32 Checksums
md5_hex = hashlib.md5(b"1:5:12:19:20").hexdigest()
crc_int = zlib.crc32(b"1:5:12:19:20")
Part 3: Master Network Templates (TCP, Select, UDP, TCP-UDP Proxy) Template 1: Single-Client TCP Server & Client # --- tcp_server.py ---
import socket, sys
ip, port = sys.argv[1], int(sys.argv[2])
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((ip, port))
server.listen(5)
print(f"TCP Server listening on {ip}:{port}")
while True:
conn, addr = server.accept()
with conn:
print(f"Connected by {addr}")
data = conn.recv(1024)
if data:
print("Received:", data.decode())
conn.sendall(b"Hello client")
# --- tcp_client.py ---
import socket, sys
ip, port = sys.argv[1], int(sys.argv[2])
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((ip, port))
client.sendall(b"Hello server")
print("Server replied:", client.recv(1024).decode())
Template 2: Multi-Client TCP Server with select.select() # --- select_tcp_server.py ---
import socket, select, sys
ip, port = sys.argv[1], int(sys.argv[2])
server = socket.socket(socket.AF_INET, socke...

Powered by Readybot.io