Non-Blocking Sockets and select()
Handle multiple connections in a single Python process using non-blocking sockets and the select module for scalable I/O multiplexing.
The Blocking Problem
A simple recv() call blocks until data arrives. A single-threaded server can therefore only serve one client at a time.
To handle many clients without threads, we use non-blocking sockets combined with an I/O multiplexer like select().
Making a Socket Non-Blocking
Call setblocking(False) on a socket. Now recv() and send() return immediately, raising BlockingIOError if they would have blocked.
import socket
s = socket.socket()
s.setblocking(False)
print('blocking mode:', s.getblocking())All lessons in this course
- Introduction to Socket API
- TCP Client-Server Sockets
- UDP Client-Server Sockets
- Non-Blocking Sockets and select()