在example in zmq documentation之后,这是我的改动。
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)
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()
然后我从终端执行它们,当发布者正在发布(即打印出行)时,订阅者永远不会离开socket.recv()
答案 0 :(得分:5)
添加
socket.setsockopt(zmq.SUBSCRIBE, "")
订阅者,做了伎俩!
这是更新的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()