gpt4 book ai didi

python - ZeroMQ Pub/Sub 最简单的例子不起作用——我做错了什么?

转载 作者:行者123 更新时间:2023-11-28 21:54:43 25 4
gpt4 key购买 nike

example in zmq documentation 之后,这是我的看法,稍作改动。

发布者.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)

订阅者.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()

然后我从终端执行它们,当发布者发布时(即打印出行),订阅者永远不会退出 socket.recv()

最佳答案

添加

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()

关于python - ZeroMQ Pub/Sub 最简单的例子不起作用——我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23797363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com