You are on page 1of 2

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

Asked 8 years, 1 month ago Active 11 months ago Viewed 10k times

can i listen to multiple sockets at once

10 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
2 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

python sockets

Share Improve this question edited Feb 26 '13 at 23:34 asked Feb 26 '13 at 23:15
Follow Calum
2,044 2 18 37

2 Answers Active Oldest Votes

Yes, there is. You need to use non-blocking calls to receive from the sockets. Check out the
select module
12
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.
Share Improve this answer edited Feb 26 '13 at 23:40 answered Feb 26 '13 at 23:33

Follow entropy
2,974 17 19

thanks that worked perfectly, this example was also really helpful – Calum Feb 26 '13 at 23:43

Glad to have been of help :) – entropy Feb 26 '13 at 23:46

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
0 this module instead, unless they want precise control over the OS-level primitives used. As
per the documentation

Share Improve this answer Follow answered May 10 '20 at 15:27


PrisionMike
21

You might also like