MatUtter MatUtter - 20 days ago 7
Python Question

How to wait for any socket to have data?

I'm implementing a socket-client which opens several sockets at the same time. Any socket may have data at a different time and I want to execute code when any socket has data and is readable.

I'm not sure how to implement this, I was looking at select.select but it seems to wait for all the sockets to be readable.

I'd like to avoid using multiprocessing to handle data on the sockets, I would like it to be serial in reading from each socket but read when there is data available.

How do I wait for any socket to be readable?

# psudo code

sockets = [sock1, sock2, sock3]

while True:
if len(sockets) == 0:
break
for sock in sockets:
if sock.has_data():
do_stuff(sock)
sockets.remove(sock)
sleep(0.1)

Answer

You can use select.select for your problem:

sockets = [sock1, sock2, sock3]
while sockets:
    rlist, _, _ = select.select(sockets, [], [])
    for sock in rlist:
        do_stuff(sock)
        sockets.remove(sock)