【问题标题】:Is the subscriber able to receive updates from multiple publishers in ZeroMQ with cpp binding?订阅者是否能够通过 cpp 绑定接收来自 ZeroMQ 中多个发布者的更新?
【发布时间】:2018-03-07 13:27:37
【问题描述】:

在我的代码中,我只能从我连接的第一个发布者(端口 5556)接收消息。

那么在连接到第二个(5557)之前,我需要关闭第一个连接(5556)吗?

如果是,那么在ZeroMQ指南的声明中

“订阅者可以连接到多个发布者,每次使用一个连接调用。然后数据将到达并被交错(“公平排队”),因此没有一个发布者会淹没其他发布者。”

短语“每次使用一个连接调用”是否意味着我们需要在连接到第二个发布者之前关闭第一个连接?

如何同时连接到多个发布者以接收来自两者的消息。

代码:

#include <zmq.hpp>
#include

int main (int argc, char *argv[])
{
zmq::context_t context (1);
zmq::socket_t subscriber (context, ZMQ_SUB);

subscriber.connect("tcp://localhost:5556");
subscriber.connect("tcp://localhost:5557");
subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);//subscribe to all messages

//  Process 10 updates
int update_nbr;
for (update_nbr = 0; update_nbr < 10 ; update_nbr++) {

    zmq::message_t update;
    subscriber.recv (&update);

 // Prints only the data from publisher bound to port 5556

    std::string updt = std::string(static_cast<char*>(update.data()), update.size());
    std::cout << "Received Update/Messages/TaskList " << update_nbr <<" : "<< updt << std::endl;

}
return 0;
}

【问题讨论】:

    标签: c++ zeromq publish-subscribe


    【解决方案1】:

    这是否意味着我们需要在第二个之前关闭第一个?

    没有。

    无需.close() 即可再次调用.connect(...) 方法。


    如何连接到多个PUB-s 以接收来自两者的消息?

    如果公平队列 SUB 端策略和 { PUB | SUB } 端相同的主题过滤策略逻辑处理(取决于版本.. . ) 仍然是合理的:

    int main (int argc, char *argv[])
    {
    zmq::context_t context (1);
    zmq::socket_t subscriber (context, ZMQ_SUB);
    
    subscriber.connect( "tcp://localhost:5556" ); // ipc://first   will have less
    subscriber.connect( "tcp://localhost:5557" ); // ipc://second  protocol overheads
    
    subscriber.setsockopt( ZMQ_SUBSCRIBE, "", 0 );// subscribe to .recv() any message
    ...
    }
    

    如果不是,请使用多个SUB-side 套接字实例,每个.connect()-ed 到各自的非平衡PUB-s 并使用非阻塞.poll() 在事件循环中,经过精心设计,以便在每个处理的非连贯主题过滤策略下临时监控和处理所有非平衡消息到达事件流每个PUB/SUB(或XPUB/XSUB)共存消息“事件流”。

    【讨论】:

    • 我应该写subscriber.connect("ipc://publisher.cpp");如何提端口号?@user3666197
    • 不,你不应该。不,ipc:// 传输类连接机制没有“端口号”。最好的下一步,如果希望开始进一步试验ipc:// 传输级部署,将重新阅读基本系统文档,了解如何为这个高效的 IPC 工具设置和配置系统资源 >>​​> @ 987654321@
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多