Building an Event-Driven Non-Blocking Echo Server
Pairing non-blocking listener sockets with `selectors` allows a single OS thread to accept new client connections and read incoming requests concurrently without threads or processes 📡.
import selectors
import socket
sel = selectors.DefaultSelector()
s1, s2 = socket.socketpair()
s1.setblocking(False)
def on_read(conn):
data = conn.recv(1024)
print(f"Echo received: {data.decode()} 📡")
sel.register(s1, selectors.EVENT_READ, data=on_read)
s2.sendall(b"EVENT_DRIVEN_ECHO")
for key, mask in sel.select(timeout=1.0):
callback = key.data
callback(key.fileobj)
sel.unregister(s1)
sel.close()
s1.close()
s2.close()
# 3. Building an Event-Driven Non-Blocking Echo Server Pairing non-blocking listener sockets with `selectors` allows a single OS thread to accept new client connections and read incoming requests concurrently without threads or processes 📡. ```python import selectors import socket sel = selectors.DefaultSelector() s1, s2 = socket.socketpair() s1.setblocking(False) def on_read(conn): data = conn.recv(1024) print(f"Echo received: {data.decode()} 📡") sel.register(s1, selectors.EVENT_READ, data=on_read) s2.sendall(b"EVENT_DRIVEN_ECHO") for key, mask in sel.select(timeout=1.0): callback = key.data callback(key.fileobj) sel.unregister(s1) sel.close() s1.close() s2.close() ``` This callback architecture is the fundamental building block of Node.js (`libuv`), Twisted, Tornado, and Python's own `asyncio`. A single event loop manages millions of multiplexed connection state transitions flawlessly ⚡! --- ### Question What pattern allows an event loop to route incoming socket events to the appropriate function dynamically? 🧠- [ ] a. Storing the handler callable in the selector's `data` payload and invoking `key.data(key.fileobj)` on readiness 📡 - [ ] b. Querying system syslog files for function names - [ ] c. Spawning an OS sub-process for every file descriptor - [ ] d. Evaluating Python source strings using `eval()` --- ### Challenge Register `s1` with callback `on_read(conn)` that returns `conn.recv(32).decode()`. Send `b'HI'` via `s2`, invoke callback via `key.data(key.fileobj)`, and print the result. 🎯 <details> <summary>Solution</summary> ```python import selectors import socket sel = selectors.DefaultSelector() s1, s2 = socket.socketpair() s1.setblocking(False) def on_read(conn): return conn.recv(32).decode() sel.register(s1, selectors.EVENT_READ, on_read) s2.sendall(b'HI') res = None for key, mask in sel.select(timeout=1.0): res = key.data(key.fileobj) sel.unregister(s1) sel.close() s1.close() s2.close() print(res) ``` </details>