How To Wait For Any Socket To Have Data?
I'm implementing a socket-client which opens several sockets at the same time. Any socket may have data at a different time and I want to execute code when any socket has data and
Solution 1:
You can use select.select
for your problem:
sockets = [sock1, sock2, sock3]
while sockets:
rlist, _, _ = select.select(sockets, [], [])
for sock in rlist:
do_stuff(sock)
sockets.remove(sock)
Solution 2:
If you are on POSIX, take a look at select.poll
:
import socket
importselect
p = select.poll()
s1 = socket.socket()
s2 = socket.socket()
# call connect on sockets here...
p.register(s1, select.POLLIN)
p.register(s2, select.POLLIN)
p.poll()
Solution 3:
If you're using Python 3.4 or newer there is the selectors
module in the standard library. It will use the "best" I/O multiplexing implementation that your system offers (select, poll, kqueue...) There's a simple echo server example at the end of the documentation page https://docs.python.org/3/library/selectors.html
There's a backport of this for older Python versions available as well.
Post a Comment for "How To Wait For Any Socket To Have Data?"