0Pricing
Linux Networking & TCP/IP for Developers · Leçon

Sockets non bloquants et select()

Gérez plusieurs connexions dans un seul processus Python à l’aide de sockets non bloquants et du module select pour une multiplexation des entrées-sorties évolutive.

Sockets non bloquants et select() est une leçon Linux Networking & TCP/IP for Developers gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Linux Networking & TCP/IP for Developers, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Linux Networking & TCP/IP for Developers comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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 sockets
  • select() to discover ready sockets
  • accept on the listening socket, recv on clients
  • Scale up with poll, epoll, or the selectors module

This builds on your TCP and UDP socket lessons toward scalable network services.

Questions Fréquemment Posées

La leçon « Sockets non bloquants et select() » est-elle gratuite ?

Oui — le texte complet de « Sockets non bloquants et select() » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Linux Networking & TCP/IP for Developers, passe à CoddyKit PRO. Le cours Linux Networking & TCP/IP for Developers comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Sockets non bloquants et select() » ?

Gérez plusieurs connexions dans un seul processus Python à l’aide de sockets non bloquants et du module select pour une multiplexation des entrées-sorties évolutive. Tu pratiques Linux Networking & TCP/IP for Developers avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Linux Networking & TCP/IP for Developers ?

Aucune expérience préalable n'est requise. Linux Networking & TCP/IP for Developers sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.

Combien de temps prend la leçon « Sockets non bloquants et select() » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Linux Networking & TCP/IP for Developers ?

Oui. Chaque leçon Linux Networking & TCP/IP for Developers inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Introduction à l’API des sockets
  2. Sockets TCP client-serveur
  3. Sockets UDP client-serveur
  4. Sockets non bloquants et select()
← Retour à Linux Networking & TCP/IP for Developers