python - 有没有办法一次收听多个 python 套接字

标签 python sockets

我可以同时监听多个套接字吗

我现在用来监视套接字的代码是:

while True:
    for sock in socks:
        data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
        print "received message:", data

但那是在排队:

data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes

直到收到消息。

有没有办法让它同时监听多个套接字

编辑:不确定它是否完全相关,但我正在使用 UDP

最佳答案

是的,有。您需要使用非阻塞调用从套接字接收。查看select module

如果您正在从套接字读取数据,那么您可以使用它:

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

注意:您还可以将额外参数传递给 select.select(),这是一个超时参数。如果没有套接字就绪,这将防止它永远阻塞。

关于python - 有没有办法一次收听多个 python 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15101333/

相关文章:

python - 这些正则表达式有什么区别: '^From .*@([^ ]*)' & '^From .*@(\S+)' ?

Java TCP 多用户聊天服务器客户端与服务器的连接存在问题

java - 如何重新初始化数据包的缓冲区?

node.js - Socket.io 断开 Ping 超时错误

java - Executorservice worker 没有在单独的线程中运行

python - 狮身人面像 : how to cross-reference a target generated by a custom directive

python - 获取Shopee电商网站产品名称的工作相对xpath

python - 获取一小时过去的微秒

带有重复键或无的 Python dict

java - 在 Java 中从套接字读取字节