无法通过IPC接收ZeroMQ Python绑定的消息

24 投票
1 回答
9509 浏览
提问于 2025-04-16 12:11

我正在尝试通过进程间通信(IPC)实现发布/订阅模式。如果我把下面的代码改成让订阅者绑定到 "tcp://*:5000",而发布者连接到 "tcp://localhost:5000",那样是可以工作的,但我就是无法通过IPC来实现。请问我哪里做错了?

订阅者代码(subscriber.py)

import zmq, json

def main():
    context = zmq.Context()
    subscriber = context.socket(zmq.SUB)
    subscriber.bind("ipc://test")
    subscriber.setsockopt(zmq.SUBSCRIBE, '')
    while True:
        print subscriber.recv()

if __name__ == "__main__":
    main()

发布者代码(publisher.py)

import zmq, json, time

def main():
    context = zmq.Context()
    publisher = context.socket(zmq.PUB)
    publisher.connect("ipc://test")
    while True:
        publisher.send( "hello world" )
        time.sleep( 1 )

if __name__ == "__main__":
    main()

1 个回答

29

最可能的原因是你在不同的文件夹里运行发布者。试试用绝对路径来指定管道的位置,比如:"ipc:///tmp/test.pipe"。你现在的写法是相对于当前工作目录的。

撰写回答