Is there a way to listen to multiple python sockets at once

Can I listen to multiple sockets at once

The code I'm currently using to monitor sockets is:

while True:
    for sock in socks:
        data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
        print "received message:", data

but which is waiting in line:

data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes

until you get a message.

Is there any way to make it listen to multiple sockets at once

EDIT: not sure if this is completely up to date, but I'm using UDP

+5
source share
1 answer

Yes there is. You need to use non-blocking calls to receive from sockets. Check select module

If you are reading from sockets, here is how you use it:

while True:
    # this will block until at least one socket is ready
    ready_socks,_,_ = select.select(socks, [], []) 
    for sock in ready_socks:
        data, addr = sock.recvfrom(1024) # This is will not block
        print "received message:", data

Note. You can also pass an additional argument select.select(), which is a timeout. This will prevent blocking forever if the sockets are not ready.

+9

All Articles