Linux Networking & TCP/IP for Developers · Lezione

Socket non bloccanti e select()

Gestisca più connessioni in un singolo processo Python usando socket non bloccanti e il modulo select per un I/O multiplexing scalabile.

Lezione 4 di 413 passaggi

Socket non bloccanti e select() è una lezione Linux Networking & TCP/IP for Developers gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Linux Networking & TCP/IP for Developers, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Linux Networking & TCP/IP for Developers include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Gratis per iniziare

Impara Linux Networking & TCP/IP for Developers con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Socket non bloccanti e select()» è gratuita?

Sì — il testo completo di «Socket non bloccanti e select()» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Linux Networking & TCP/IP for Developers, passa a CoddyKit PRO. Il corso Linux Networking & TCP/IP for Developers include 4 lezioni in totale.

Cosa imparerò in «Socket non bloccanti e select()»?

Gestisca più connessioni in un singolo processo Python usando socket non bloccanti e il modulo select per un I/O multiplexing scalabile. Eserciti Linux Networking & TCP/IP for Developers con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Linux Networking & TCP/IP for Developers?

Non è richiesta alcuna esperienza precedente. Linux Networking & TCP/IP for Developers su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Socket non bloccanti e select()»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Linux Networking & TCP/IP for Developers?

Sì. Ogni lezione Linux Networking & TCP/IP for Developers include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Introduzione alle Socket API
  2. Socket client-server TCP
  3. Socket client-server UDP
  4. Socket non bloccanti e select()
← Torna a Linux Networking & TCP/IP for Developers