i've noticed weird behavior zmq.pub, requires have while loop send message. example:
imagine have sub waiting pub:
context = zmq.context() subscriber = context.socket(zmq.sub) subscriber.setsockopt(zmq.subscribe, '') subscriber.connect ('tcp://*:5555') while true: msg = socket.recv() and want send message pub:
context = zmq.context() publisher = context.socket(zmq.pub) publisher.bind('tcp://*:%5555') publisher.send(''.join(sys.argv[1])) this message won't reach sub reason. can fix adding while or for loop before sending message publisher.send(''.join(sys.argv[1]))
why that? have have loop publisher distribute messages multiple workers?
actually, there few problems here.
first, code you've posted has number of errors in (for example, can't connect tcp://*:5555), i'll assume it's representative of you're trying do.
update
i'm going leave original answer below, because think it's still useful although not directly relevant question (possibly due morning caffeine deficit, knows?).
since publisher calling send single message , exiting immediately, subscribers never have time connect(). typically expect code calling bind long-running process. if insert sleep between bind , send call, things work expected:
ctx = zmq.context() pub = ctx.socket(zmq.pub) pub.bind('tcp://*:5555') time.sleep(1) pub.send('message 1') this works fine, assuming following subscriber:
ctx = zmq.context() sub = ctx.socket(zmq.sub) sub.setsockopt(zmq.subscribe, '') sub.connect('tcp://localhost:5555') while true: msg = sub.recv() print msg however, isn't great solution...anything using sleep synchronization bound fail. different way of solving have publisher open both pub socket , rep socket. send message subscribers, tool open req socket broker, publish subscribers.
original answer follows
the problem you're hitting this. since having subscriber call bind , sender call connect, losing message because there delay between successful connection , subscriber subscribing messages. see question "why see different behavior when bind socket versus connect socket?" in the faq.
demonstrating code, if have subscriber:
ctx = zmq.context() sub = ctx.socket(zmq.sub) sub.setsockopt(zmq.subscribe, '') sub.bind('tcp://*:5555') while true: msg = sub.recv() print msg and following publisher:
ctx = zmq.context() pub = ctx.socket(zmq.pub) pub.connect('tcp://localhost:5555') pub.send('message 1') pub.send('message 2') time.sleep(1) pub.send('message 3') the subscriber end printing:
message 3 this because first send operations happen quickly.
this not considered problem, since pub/sub explicitly not reliable transport mechanism. in typical use case, there single publisher calling bind , multiple subscribers calling connect may not present or continuously. there no guarantee every subscriber receive every message.
if need reliably transport single message, consider req/rep socket pair instead.
Comments
Post a Comment