Sockets no bloqueantes y select()
Gestione varias conexiones en un único proceso de Python mediante sockets no bloqueantes y el módulo select para lograr una multiplexación de E/S escalable.
Sockets no bloqueantes y select() es una lección gratuita de Linux Networking & TCP/IP for Developers en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Linux Networking & TCP/IP for Developers, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Linux Networking & TCP/IP for Developers incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Preguntas frecuentes
¿La lección «Sockets no bloqueantes y select()» es gratis?
Sí — el texto completo de «Sockets no bloqueantes y select()» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Linux Networking & TCP/IP for Developers, actualiza a CoddyKit PRO. El curso de Linux Networking & TCP/IP for Developers incluye 4 lecciones en total.
¿Qué aprenderé en «Sockets no bloqueantes y select()»?
Gestione varias conexiones en un único proceso de Python mediante sockets no bloqueantes y el módulo select para lograr una multiplexación de E/S escalable. Practicas Linux Networking & TCP/IP for Developers con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Linux Networking & TCP/IP for Developers?
No se requiere experiencia previa. Linux Networking & TCP/IP for Developers en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Sockets no bloqueantes y select()»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Linux Networking & TCP/IP for Developers?
Sí. Cada lección de Linux Networking & TCP/IP for Developers incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción a la API de sockets
- Sockets TCP cliente-servidor
- Sockets UDP cliente-servidor
- Sockets no bloqueantes y select()