ノンブロッキングソケットとselect()
ノンブロッキングソケットとselectモジュールを使い、1つのPythonプロセスで複数の接続を処理するスケーラブルなI/O多重化を学びます。
「ノンブロッキングソケットとselect()」はCoddyKit上の無料Linux Networking & TCP/IP for Developersレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはLinux Networking & TCP/IP for Developers学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Linux Networking & TCP/IP for Developersコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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.
よくある質問
「ノンブロッキングソケットとselect()」レッスンは無料ですか?
はい。「ノンブロッキングソケットとselect()」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Linux Networking & TCP/IP for Developersコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Linux Networking & TCP/IP for Developersコースには全4レッスンが含まれています。
「ノンブロッキングソケットとselect()」で何を学びますか?
ノンブロッキングソケットとselectモジュールを使い、1つのPythonプロセスで複数の接続を処理するスケーラブルなI/O多重化を学びます。 ブラウザで直接実行するハンズオンコードでLinux Networking & TCP/IP for Developersを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Linux Networking & TCP/IP for Developersを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのLinux Networking & TCP/IP for Developersは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「ノンブロッキングソケットとselect()」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このLinux Networking & TCP/IP for Developersレッスンでコードを書いて実行できますか?
はい。すべてのLinux Networking & TCP/IP for Developersレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Socket API入門
- TCPクライアント・サーバーソケット
- UDPクライアント・サーバーソケット
- ノンブロッキングソケットとselect()