从Python发布时订阅不起作用
原来的问题在这里: https : //github.com/JustinTulloss/zeromq.node/issues/444
嗨,
如果我从Node.js订阅到Python的发布者,订阅者不能接收消息。 另一方面,Node-publisher可以同时发送python-subscriber和node-subscriber,python-publisher可以发送python订阅者。
节点用户:
// Generated by LiveScript 1.4.0 (function(){ var zmq, sock; zmq = require('zmq'); sock = zmq.socket('sub'); sock.connect('tcp://127.0.0.1:3000'); sock.subscribe(''); console.log('Subscriber connected to port 3000'); sock.on('message', function(message){ return console.log('Received a message related to: ', 'containing message: ', message.toString()); }); }).call(this);
节点发布者:
// Generated by LiveScript 1.4.0 (function(){ var zmq, sock; zmq = require('zmq'); sock = zmq.socket('pub'); sock.bindSync('tcp://127.0.0.1:3000'); console.log('Publisher bound to port 3000'); setInterval(function(){ console.log('Sending a multipart message envelope'); return sock.send('TestMessage(node)!'); }, 1500); }).call(this);
Python发布者
import zmq import time context = zmq.Context() publisher = context.socket(zmq.PUB) publisher.bind("tcp://127.0.0.1:3000") while True: time.sleep(1) publisher.send("TestMessage") print "Sent"
Python用户:
import zmq context = zmq.Context() socket = context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, "") socket.connect("tcp://127.0.0.1:3000") while True: string = socket.recv() print string
您需要使用仅具有一个参数(即data
)的函数更改订户sock.on()
调用:
(function(){ var zmq, sock; zmq = require('zmq'); sock = zmq.socket('sub'); sock.connect('tcp://127.0.0.1:3000'); sock.subscribe(''); console.log('Subscriber connected to port 3000'); sock.on('message', function(data){ return console.log('New message: ', data.toString()); }); }).call(this);
发布者代码应该没有任何修改,但我更喜欢(Python 3兼容)的东西:
import time context = zmq.Context() publisher = context.socket(zmq.PUB) publisher.bind("tcp://127.0.0.1:3000") while True: time.sleep(1) publisher.send(bytearray('test', 'ascii')) print('Sent test message')
问题是PyZMQ
和zeromq.node
之间的libzmq版本不匹配:
$ python >>> import zmq >>> zmq.zmq_version() '4.0.5'
和节点版本:
$ node > require('zmq').version '2.2.0'
解决scheme是:
- 卸载当前版本的libzmq:
sudo apt-get purge libzmq-dev
- 卸载当前的zeromq.node:
sudo npm uninstall zmq -g
-
安装libzmq-4.x:
sudo apt-get install libzmq3-dev
如果此步骤失败,则需要从源代码安装libzmq-4.x: https : //github.com/zeromq/libzmq
- 安装zeromq.node:
sudo npm install zmq