本文介绍了ZeroMQ (cppzmq) 订阅者带有以相同字符串开头的过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在示例发布商中使用了两个主题.两者都以相同的字符串开头.当我仅使用两个主题之一过滤订阅者中的消息时,订阅者会收到两个主题

I'm using two topics in my sample publisher. Both start with the same string. When I filter the message in a subscriber using only one of the two topics, the subscriber receives both topics

如果我使用两个不同的主题,它会起作用

If I use two different topics, it works

我的样本发布商

try (ZContext context = new ZContext()) {
    final ZMQ.Socket socket = context.createSocket(SocketType.PUB);
    socket.bind("tcp://*:5555");
    int i = 0;
    while (!Thread.currentThread().isInterrupted() && !stopped) {

        logger.debug("sending C1 message");
        final String env = "topic";
        final String msg = "Hello, world #" + i++;
        socket.sendMore(env);
        socket.send(msg);

    logger.debug("sending C2 message");

        final String env2 = "topic2";
        final String msg2 = "Hello, world #" + i++;
        socket.sendMore(env2);
        socket.send(msg2);

        try {
            sleep(5000);
        } catch (final InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

还有我的样本订阅者:

zmq::context_t ctx;
zmq::socket_t sock(ctx, zmq::socket_type::sub);
sock.connect("tcp://127.0.0.1:5555");
std::string filter="topic";
sock.setsockopt(ZMQ_SUBSCRIBE,filter.c_str(),filter.length());
while(true) {
    zmq::message_t env;
    sock.recv(&env);
    std::string env_str = std::string(static_cast<char*>(env.data()), env.size());
    std::cout << "Received Enveloppe '" << env_str << "'" << std::endl;

    zmq::message_t msg;
    sock.recv(&msg);
    std::string msg_str = std::string(static_cast<char*>(msg.data()), msg.size());
    std::cout << "Received '" << msg_str << "'" << std::endl;
}

我的订阅者应该只显示与主题topic"相关的消息,而不是两者都显示.

My subscriber should display only the message associated with the topic "topic" and not both.

推荐答案

不正确,恰恰相反.

文档在这方面很清楚.ZeroMQ API 明确指出:

Documentation is clear in this. ZeroMQ API explicitly states:

非空option_value 订阅以指定前缀开头的所有消息.多个过滤器可以附加到单个 ZMQ_SUB 套接字,在这种情况下,如果消息匹配至少一个过滤器,则应接受该消息.

+---------------+---------------+
|选项值类型 |二进制数据 |
+------------------------------+---------------+

示例:一条消息,在 PUB 端发送为:

Example:a message, dispatched on the PUB-side as:

PUB.send( "123456------------" );

将在以下任一订阅的 SUB-s 上获得 .recv()-ed:

will get .recv()-ed on either of below subscribed SUB-s:

SUB.setsockopt( zmq.SUBSCRIBE, "" );      // this one .recv()-es EVERY message
SUB.setsockopt( zmq.SUBSCRIBE, "1" );    //  this one .recv()-es "1{0+[*]}"
SUB.setsockopt( zmq.SUBSCRIBE, "12" );  //   this one .recv()-es "12{0+[*]}"
SUB.setsockopt( zmq.SUBSCRIBE, "123" );//    this one .recv()-es "123{0+[*]}"

这篇关于ZeroMQ (cppzmq) 订阅者带有以相同字符串开头的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:53