在C ++ ZMQ Publisher中,我将字符串打包在message_t中,如下所示:

int main()
{
     zmq::context_t context(1);
     zmq::socket_t socket(context, ZMQ_PUB);
     socket.bind("tcp://*:5555");
     socket.setsockopt(ZMQ_CONFLATE, 1);
     std::cout << "Server Up and Sending\n";
     while(true)
     {
          std::string str = "Hello from C++!";
          zmq::message_t msg(str.data(), str.length());
          bool ret = socket.send(msg);
          if(ret)
          {
               std::cout << "Sending\n";
          }
     }
     return 0;
}


我试图弄清楚如何在JeroMQ(Java ZMQ)中进行接收;这是我到目前为止的内容:

  ZMQ.Context context = ZMQ.context(1);
  ZMQ.Socket socket = context.socket(ZMQ.SUB);
  socket.connect("tcp://localhost:5555");
  socket.subscribe("".getBytes());
  while(true)
  {
        String msg = socket.recvStr();
        System.out.println(msg);
  }


同样在PyZMQ(Python ZMQ)中:

import zmq

context = zmq.Context()
socket = context.socket(zmq.SUB)
address = 'tcp://localhost:5555'
socket.connect(address)
socket.setsockopt_string(zmq.SUBSCRIBE, unicode(''))

print "start"
print "connecting to ", address

while True:
    try:
        msg = socket.recv_string()
        print msg


但是,我的JeroMQ尝试或PyZMQ尝试都未收到我的字符串消息。

最佳答案

尝试使用pyzmq订阅此代码段代码:

import zmq
import time

port = "5555"

context = zmq.Context()
socket = context.socket(zmq.SUB)

socket.setsockopt(zmq.SUBSCRIBE, '')
socket.setsockopt(zmq.CONFLATE, 1)  # last msg only.
socket.connect("tcp://localhost:%s" % port)  # must be placed after above options.

while 1:
    time.sleep(1)
    data = socket.recv()
    print data




[注意]:

如果不起作用,请在C ++ ZeroMQ发布者中删除以下行:


  socket.setsockopt(ZMQ_CONFLATE, 1);

10-06 15:42