从 Python 发布时订阅不起作用

Subscribe is not working while publishing from Python

Original question is here: https://github.com/JustinTulloss/zeromq.node/issues/444

嗨,

如果我从 Node.js 订阅 Python 中的发布者,订阅者将无法接收消息。另一方面,Node-publisher 可以同时发送 python-subscriber 和 node-subscriber,python-publisher 可以发送 python subscriber。

节点订阅者:

// 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 compatible):

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

问题是 PyZMQzeromq.node 之间的 libzmq 版本不匹配:

$ python 
>>> import zmq
>>> zmq.zmq_version()
'4.0.5'

和节点版本:

$ node
> require('zmq').version
'2.2.0'

解决方法是:

  1. 卸载当前版本的 libzmq:sudo apt-get purge libzmq-dev
  2. 卸载当前 zeromq.node:sudo npm uninstall zmq -g
  3. 安装 libzmq-4.x: sudo apt-get install libzmq3-dev

    if this step fails, you need to install libzmq-4.x from source: https://github.com/zeromq/libzmq

  4. 安装zeromq.node:sudo npm install zmq