Is There A Way To Listen To Multiple Python Sockets at Once - Stack Overflow
Is There A Way To Listen To Multiple Python Sockets at Once - Stack Overflow
Asked 8 years, 1 month ago Active 11 months ago Viewed 10k times
while True:
for sock in socks:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
2 print "received message:", data
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
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
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