6

I'm write a zeromq demo with Forwarder device (with pyzmq)

Here are the codes(reference to 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')

I run python forwarder.py, python sub.py in the terminal

then run python pub.py, the subscriber can't get the message. However, if I sleep a little time(for example 0.01s) before send, it works.

So my problem is, why have I sleep before send? thanks.

wong2
  • 34,358
  • 48
  • 134
  • 179

1 Answers1

11

It's known as Slow Joiner syndrome. Read the guide, there are ways to avoid it using pub/sub syncing.

raffian
  • 31,267
  • 26
  • 103
  • 174
  • 4
    specifically, look at the [pub-sub synchronization example](http://zguide.zeromq.org/page%3aall#Node-Coordination) to see it working. As the figure shows, you'll use an additional REP/REQ pair of sockets to sync your [pub](http://zguide.zeromq.org/py:syncpub) and [sub](http://zguide.zeromq.org/py:syncsub) sockets. – tutuDajuju Oct 18 '13 at 14:30
  • It also says, that the example it shows has an unrobust 1 second delay in the subscriber, and then suggests you basically need to send bogus data from the publisher to the subscriber until everything is flushed through. Look at the "more robust model" blurb at the very end. – Mark Lakata Sep 23 '16 at 02:46
  • 4
    Everything is 404. – Matteo Ragni Nov 11 '20 at 15:08