Skip to main content
 首页 » 编程设计

python之Pub Sub 只能在一个方向上工作

2025年05月04日11telwanggs

所以我正在使用 ZeroMQ 的 python 绑定(bind),试图将消息发送到网络上的几个树莓派,用于一个艺术项目。问题是我在树莓派上没有收到任何消息。更糟糕的是,我可以:

  • 从 raspberry pi 发布消息并在我的笔记本电脑 (osx) 上接收它们
  • REQ/REP 模型双向工作(osx -> RPI 和 RPI -> osx)

我认为这与两台设备上的防火墙有关,我在两台设备上都禁用了防火墙。没有运气。

有人有什么想法吗?这是我的代码:

ZMQ Publisher

import time 
import zmq 
 
 
def main(): 
    port = 5563 
 
    # Prepare our context and publisher 
    context = zmq.Context() 
    publisher = context.socket(zmq.PUB) 
    publisher.bind("tcp://*:" + str(port)) 
 
    while True: 
        # Write two messages, each with an envelope and content 
        publisher.send_multipart([b"A", b"We don't want to see this"]) 
        publisher.send_multipart([b"B", b"We would like to see this"]) 
        time.sleep(1) 
 
    # We never get here but clean up anyhow 
    publisher.close() 
    context.term() 
 
if __name__ == "__main__": 
    main() 

ZMQ Subscriber

import zmq 
import sys 
 
 
def main(): 
    ip = sys.argv[1] 
    port = 5563 
    string = "tcp://" + ip + ":" + str(port) 
 
    # Prepare our context and publisher 
    context = zmq.Context() 
    subscriber = context.socket(zmq.SUB) 
    subscriber.connect(string) 
    subscriber.setsockopt(zmq.SUBSCRIBE, b"B") 
 
    while True: 
        # Read envelope with address 
        [address, contents] = subscriber.recv_multipart() 
        print("[%s] %s" % (address, contents)) 
 
    # We never get here but clean up anyhow 
    subscriber.close() 
    context.term() 
 
if __name__ == "__main__": 
    main() 

请您参考如下方法:

已解决。有两个问题:

首先-因为我使用的是 python3,所以我必须确保在更新/安装 python 模块时使用的是 pip-3.2 命令

其次 - 在我的笔记本电脑上,我使用的是 pyzmq 14.6.0,而我在 PI 上使用的是 2.2.0。我已经更新了它,但是使用了 pip 而不是 pip-3.2。一旦我正确更新了 pyzmq,它就会按预期工作。