Event-Driven Socket Programs
Socket programs, particularly servers, must often perform many tasks at once. Example 20-1 accepts a connection request, then serves a single client until that client has finished—other requests must wait. This is not acceptable for servers in production use. Clients cannot wait too long: the server must be able to service multiple clients at once.
One way to let your program perform several tasks at once is threading, covered in Threads in Python. Module SocketServer optionally supports threading, as covered in The SocketServer Module. An alternative to threading that can offer better performance and scalability is event-driven (also known as asynchronous) programming.
An event-driven program sits in an event loop and waits for events. In networking, typical events are “a client requests connection,” “data arrived on a socket,” and “a socket is available for writing.” The program responds to each event by executing a small slice of work to service that event, then goes back to the event loop to wait for the next event. The Python library provides minimal support for event-driven network programming with the low-level select module and the higher-level asyncore and asynchat modules. Much richer support for event-driven programming is in the Twisted package (available at http://www.twistedmatrix.com), particularly in subpackage twisted.internet.
The select Module
The select module exposes a cross-platform, low-level function to implement asynchronous network ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access