我正在使用Forwarder设备(使用pyzmq)编写一个zeromq演示
以下是代码(对https://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/devices/forwarder.html的引用):
forwarder.py
import zmq
context = zmq.Context()
frontend = context.socket(zmq.SUB)
frontend.bind('tcp://*:5559')
frontend.setsockopt(zmq.SUBSCRIBE, '')
backend = context.socket(zmq.PUB)
backend.bind('tcp://*:5560')
zmq.device(zmq.FORWARDER, frontend, backend)
sub.py
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://localhost:5560')
socket.setsockopt(zmq.SUBSCRIBE, '')
while True:
print socket.recv()
pub.py
import zmq, time
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.connect('tcp://localhost:5559')
# time.sleep(0.01)
socket.send('9 hahah')
我在终端
中运行python forwarder.py
,python sub.py
然后运行python pub.py
,订阅者无法获取消息。但是,如果我在发送之前睡了一点时间(例如0.01秒),它就会起作用。
所以我的问题是,为什么我发送前sleep
?感谢。