PYZMQ没有收到Python 2.7和Python 3.5之间的消息
问题描述:
似乎python 2.7和python 3.5之间的字节数组和str类型是pyzmq PUB/SUB的一个问题。 我必须在python 2.7中使用pub/sub broker,而在python 3.5中使用另一个。 我有订阅两个pub/sub brokers的订户,但它没有收到所有发布的消息。 如何让我的发布/订阅经纪人订阅并重新发布那里发布的所有消息IP:端口?PYZMQ没有收到Python 2.7和Python 3.5之间的消息
示例代码:
def subscribeformessages(self):
context = zmq.Context(1)
xsub = context.socket(zmq.SUB)
xsub_url = "tcp://%s:%s" % (self.ipaddress, self.xsub_url)
xsub.setsockopt_string(zmq.SUBSCRIBE, '')
xsub.setsockopt(zmq.SUBSCRIBE, b'')
if not is_py2:
xsub.setsockopt_string(zmq.SUBSCRIBE, "")
else:
xsub.setsockopt(zmq.SUBSCRIBE, "")
xsub.setsockopt(zmq.SUBSCRIBE, b"")
xsub.setsockopt_unicode(zmq.SUBSCRIBE, u"", encoding='utf-8')
xsub.setsockopt_string(zmq.SUBSCRIBE, u"")
xsub.connect(xsub_url)
try:
while self.running:
try:
time.sleep(.2)
receive = xsub.recv_multipart()
self.print_message_queue.put("sub recv\'d: %s" % receive)
self.pub_local_que.put(receive)
self.publish_queue.put(receive)
except zmq.ZMQError as err:
print(err)
....
出版商样本:
def sendtopicerequesttoexchange(self):
context = zmq.Context(1).instance()
sock = context.socket(zmq.PUB)
sock.linger = 0
try:
sock.bind("tcp://ip:port")
except:
sock.connect("tcp://ip:port")
topicxml = xmltree.Element("MessageXML")
topicxml.attrib['NodeAddr'] = '040000846'
topicxml.attrib['Payload'] = 'HeyBob'
replymsg = xmltree.tostring(topicxml)
msg = [str.encode("send.downlink"), str(replymsg).encode('utf-8')]
msg[0] = str(msg[0]).encode('utf-8')
try:
count = 0
while True:
time.sleep(4)
sock.send_multipart(msg)
print("msg %s" %(msg))
count += 1
if count > 1:
break
time.sleep(.2)
except Exception as bob:
print(bob)
finally:
time.sleep(5)
sock.setsockopt(zmq.LINGER, 0)
sock.close()
什么想法?
答
我找到了一个答案在这里:http://pyzmq.readthedocs.io/en/latest/pyversions.html
我改变了出版物:
def sendtoexchange_pete(self):
context = zmq.Context(1).instance()
sock = context.socket(zmq.PUB)
sock.linger = 0
try:
sock.bind("tcp://ip:port")
except:
sock.connect("tcp://ip:port")
topicxml = xmltree.Element("Downlink_75")
topicxml.attrib["NodeAddr"] = "$301$0-0-0-040000846"
topicxml.attrib["Payload"] = "HeyBob Pete\'s Xchnge 75"
replymsg = xmltree.tostring(topicxml)
# By changing to force bytes I was able to get the to work
msg = [b'send.downlink', b'%s' % replymsg]
try:
count = 0
while True:
time.sleep(4)
sock.send_multipart(msg)
print("msg %s" %(msg))
.....
在这里找到了答案:http://pyzmq.readthedocs.io/en/latest/pyversions.html确保强制字节数组b'%s' – user2106070