Nicht blockierende Sockets und select()
Verarbeiten Sie mehrere Verbindungen in einem einzigen Python-Prozess mithilfe nicht blockierender Sockets und des select-Moduls für skalierbares I/O-Multiplexing.
Nicht blockierende Sockets und select() ist eine kostenlose Linux Networking & TCP/IP for Developers-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Linux Networking & TCP/IP for Developers-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Linux Networking & TCP/IP for Developers-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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())Introducing select()
select.select() watches lists of sockets and tells you which are ready.
It takes three lists: read, write, and error, and returns the subsets that are ready.
import select
readable, writable, errored = select.select(inputs, outputs, inputs)The Server Setup
Create a listening socket, set it non-blocking, and add it to the inputs list. The listening socket becoming 'readable' means a new connection is waiting.
server = socket.socket()
server.setblocking(False)
server.bind(('localhost', 9000))
server.listen()
inputs = [server]Accepting New Connections
When the listening socket is in the readable list, call accept(). Make the new client socket non-blocking and add it to inputs too.
if s is server:
conn, addr = server.accept()
conn.setblocking(False)
inputs.append(conn)Reading from Clients
For any other readable socket, call recv(). An empty bytes result means the client closed the connection, so remove it from inputs and close it.
data = s.recv(1024)
if data:
print('got', data)
else:
inputs.remove(s)
s.close()The Full Event Loop
Wrap accept and read logic in a while True loop driven by select(). This is the heart of an event-driven server.
while inputs:
readable, _, _ = select.select(inputs, [], [])
for s in readable:
handle(s)Handling Writes
For high-throughput servers you also track the writable list. Only send when the OS says the socket can accept data, avoiding partial-send stalls.
readable, writable, _ = select.select(inputs, outputs, [])
for s in writable:
s.send(pending[s])Beyond select: poll and epoll
select() is limited by the FD_SETSIZE constant and scans all sockets each call.
For thousands of connections, Linux offers select.poll() and the more scalable select.epoll(), which scale far better.
Where selectors Fits In
The high-level selectors module wraps the best available backend (epoll/kqueue) behind one API. Most production code uses it instead of raw select.
import selectors
sel = selectors.DefaultSelector()
sel.register(server, selectors.EVENT_READ)Timeouts
Passing a timeout to select() lets the loop wake periodically even with no I/O, useful for housekeeping. A timeout of 0 polls without blocking.
readable, _, _ = select.select(inputs, [], [], 1.0)
if not readable:
print('no activity this second')Quick Check
Test your multiplexing knowledge.
Recap
You can now build a single-threaded multi-client server:
setblocking(False)for non-blocking socketsselect()to discover ready sockets- accept on the listening socket, recv on clients
- Scale up with
poll,epoll, or theselectorsmodule
This builds on your TCP and UDP socket lessons toward scalable network services.
Häufig gestellte Fragen
Ist die Lektion „Nicht blockierende Sockets und select()“ kostenlos?
Ja — der vollständige Text von „Nicht blockierende Sockets und select()“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Linux Networking & TCP/IP for Developers-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Linux Networking & TCP/IP for Developers-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Nicht blockierende Sockets und select()“?
Verarbeiten Sie mehrere Verbindungen in einem einzigen Python-Prozess mithilfe nicht blockierender Sockets und des select-Moduls für skalierbares I/O-Multiplexing. Du übst Linux Networking & TCP/IP for Developers mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Linux Networking & TCP/IP for Developers zu starten?
Keine Vorkenntnisse erforderlich. Linux Networking & TCP/IP for Developers auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Nicht blockierende Sockets und select()“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Linux Networking & TCP/IP for Developers-Lektion Code schreiben und ausführen?
Ja. Jede Linux Networking & TCP/IP for Developers-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Einführung in die Socket-API
- TCP-Client-Server-Sockets
- UDP-Client-Server-Sockets
- Nicht blockierende Sockets und select()