Reputation: 2130
can i listen to multiple sockets at once
The code i am using to monitor the sockets at the moment is:
while True:
for sock in socks:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
but that waits at the line:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
until it recieves a message.
Is there a way to make it listen to multiple sockets at once
EDIT: not sure if it is completely relevant but i am using UDP
Upvotes: 11
Views: 15482
Reputation: 91
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
Upvotes: 3
Reputation: 3144
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.
Upvotes: 15