Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZeroMQ Pub/Sub simplest example is not working - What am I doing wrong?

Following the example in zmq documentation, here is my take with minor changes.

publisher.py

import zmq
import random
import time

port = "5556"

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://127.0.0.1:%s" % port)


while True:
    topic = random.randrange(9999,10005)
    messagedata = random.randrange(1,215) - 80
    print "%d %d" % (topic, messagedata)
    socket.send("%d %d" % (topic, messagedata))
    time.sleep(1)

subscriber.py

import sys
import zmq

port = "5556"

context = zmq.Context()
socket = context.socket(zmq.SUB)

print "Collecting updates from weather server..."
socket.connect ("tcp://127.0.0.1:%s" % port)


while True:
    print socket.recv()

I then execute them from terminal, and while publisher is publishing (i.e. printing outs the lines), subscriber never gets out of socket.recv()

like image 754
Tzury Bar Yochay Avatar asked Oct 22 '25 00:10

Tzury Bar Yochay


1 Answers

adding

socket.setsockopt(zmq.SUBSCRIBE, "")

to subscriber, did the trick!

here is the updated subscriber.py

import sys
import zmq

port = "5556"

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, "")

print "Collecting updates from weather server..."
socket.connect ("tcp://127.0.0.1:%s" % port)

while True:
    print socket.recv()
like image 192
Tzury Bar Yochay Avatar answered Oct 23 '25 14:10

Tzury Bar Yochay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!