【问题标题】:Why does my C++ ZeroMQ subscriber not receive any data?为什么我的 C++ ZeroMQ 订阅者收不到任何数据?
【发布时间】:2017-01-31 04:37:18
【问题描述】:

我的 (Python) 发布者:

import zmq
import time

context = zmq.Context()
socket = context.socket(zmq.PUB)
connectStr = "tcp://*:%d" % 5563
socket.bind(connectStr)

messageNum = 0
while True:
    ++messageNum
    message = "Testing %d"%messageNum
    print("Sending.. '%s'"%message)
    socket.send_string(message)
    time.sleep(1)
    messageNum += 1

我的 (C++) 订阅者(在 GTest 中运行):

TEST(ZeroMqPubSubTest, SubscribeGetsData)
{

    // Set up the subscriber we'll use to receive the message.
    zmq::context_t context;
    zmq::socket_t subscriber(context, ZMQ_SUB);
    // Connect to the publisher
    subscriber.connect("tcp://127.0.0.1:5563");
    subscriber.setsockopt(ZMQ_SUBSCRIBE, ""); // Set the filter blank so we receive everything

    zmq::message_t response(0);
    EXPECT_TRUE(subscriber.recv(&response));
}

我启动发布者,然后启动订阅者。后者永远不会返回。

如果我运行一个 Python 订阅者做(我认为)完全相同的事情..

import zmq

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect ("tcp://127.0.0.1:5563")
socket.setsockopt_string(zmq.SUBSCRIBE, "")

print ("Waiting for data...")
while True:
    message = socket.recv()
    print ("Got some data:",message)

..它工作正常:

等待数据...

得到一些数据:b'Testing 8'

得到一些数据:b'Testing 9'

【问题讨论】:

    标签: python c++ zeromq


    【解决方案1】:

    setsockoptzmq.hpp 中定义了两个重载:

     template<typename T> void setsockopt(int option_, T const& optval)
     {
         setsockopt(option_, &optval, sizeof(T) );
     }
    
     inline void setsockopt (int option_, const void *optval_, size_t optvallen_)
     {
         int rc = zmq_setsockopt (ptr, option_, optval_, optvallen_);
         if (rc != 0)
             throw error_t ();
     }
    

    通过只提供两个参数,您隐式使用了第一个重载,它假定值长度为sizeof(T)。这解析为 1,因为 "" 是一个以零结尾的字符数组。要传入一个空字符串,您需要使用第二个重载并指定长度为 0:

    subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);
    

    或者,使用零大小的数据类型:

    char none[0];
    subscriber.setsockopt(ZMQ_SUBSCRIBE, none);
    

    【讨论】:

    • 关注@kazemakase。我仍在学习 ZeroMQ 的精妙之处,似乎 cpp 接口的某些方面尤其存在一些问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多