Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZeroMQ PubSub not working w\ Pyzmq

There is probably something very small that I am missing but I am unable to get a simple pub-sub example working in Python using the official Pyzmq package (https://github.com/zeromq/pyzmq).

I am using the latest ZeroMQ stable release 4.0.3 and am able to get a simple example working pretty easily in c. I've tried on both a Mac and Ubuntu machine. I look forward to any input on this;)

Here's my code:

sub.py

import zmq

ctx = zmq.Context()
s = ctx.socket(zmq.SUB)
s.connect("tcp://127.0.0.1:5567")
s.setsockopt(zmq.SUBSCRIBE,'')

while True:
    print 'waiting...'
    msg = s.recv()
    print 'received:', msg

pub.py

import zmq

ctx = zmq.Context()
s = ctx.socket(zmq.PUB)
s.bind("tcp://*:5567")

for i in range(100):
    s.send("test")
like image 446
Stephen Avatar asked Dec 18 '13 12:12

Stephen


1 Answers

Assuming that you launch subscriber first and then publisher, subscriber eternally tries to connect to publisher. When publisher appears, the connection procedure on the subscriber's side takes some time and your publisher doesn't really care about this. While it fires with messages as soon as it can, subscriber is trying to establish connection. When connection is established and subscriber is ready to receive, publisher is already finished its work.

Solution: give subscriber some time by adding sleep to publisher code:

import zmq
import time

ctx = zmq.Context()
s = ctx.socket(zmq.PUB)
s.bind("tcp://*:5567")

time.sleep(1)
for i in range(100):
    s.send("test")
like image 103
Dan Kruchinin Avatar answered Oct 13 '22 12:10

Dan Kruchinin