How to wait for any socket to have data?

微笑、不失礼 提交于 2019-12-12 04:29:34

问题


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 is readable.

I'm not sure how to implement this, I was looking at select.select but it seems to wait for all the sockets to be readable.

I'd like to avoid using multiprocessing to handle data on the sockets, I would like it to be serial in reading from each socket but read when there is data available.

How do I wait for any socket to be readable?

# psudo code

sockets = [sock1, sock2, sock3]

while True:
  if len(sockets) == 0:
    break
  for sock in sockets:
    if sock.has_data():
      do_stuff(sock)
      sockets.remove(sock)
  sleep(0.1)

回答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)



回答2:


If you are on POSIX, take a look at select.poll:

import socket
import select
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()



回答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.



来源:https://stackoverflow.com/questions/40641686/how-to-wait-for-any-socket-to-have-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!