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

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

If you are reading from the 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 extra argument to select.select() which is a timeout. This will keep it from blocking forever if no sockets become ready.


A slight update to entropy's answer for Python 3: The selectors module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use this module instead, unless they want precise control over the OS-level primitives used. As per the documentation

Tags:

Python

Sockets