ZeroMQ Multipart消息第二部分0大小

时间:2017-08-21 23:34:34

标签: c++ zeromq

我试图在ZMQ 4.2.3和cppzmq中使用子/ pub模式接收多部分消息我能够成功发送和接收单部分消息但是当我尝试读取时第二帧它的大小总是为0.我完全感到困惑的是使用NetMQ的C#版本没有问题地读取第二帧,这让我相信它正在被正确发送。我知道我错过了一些东西,但今天是我试图找出什么没有成功的第二天。

这是我的酒吧代码

#include <iostream>
#include "zmq_addon.hpp"
void main()
{
    zmq::context_t ctx = zmq::context_t();
    zmq::socket_t pub = zmq::socket_t(ctx, zmq::socket_type::pub);
    try
    {
        //binding using localhost gives an error about invalid device?
        pub.bind("tcp://*:8845");
    }
    catch (...)
    {
        std::cout << zmq_strerror(zmq_errno());
        std::cin.get();
        return;
    }
    byte topic = 8;
    std::string id = "ragefire.bob";
    while (true)
    {
        std::cout << "Spam\n";
        pub.send(id.c_str(), id.length(), ZMQ_SNDMORE);
        pub.send("foo", 3);
    }
}

我的C ++子代码

#include <iostream>
#include "zmq_addon.hpp"
int main()
{
    zmq::context_t ctx = zmq::context_t();
    zmq::socket_t sub = zmq::socket_t(ctx, zmq::socket_type::sub);
    sub.connect("tcp://localhost:8845");
    std::string id = "ragefire.bob";
    sub.setsockopt(ZMQ_SUBSCRIBE, id.c_str(), id.length());
    while (true)
    {
        zmq::message_t msg;
        if(sub.recv(&msg,ZMQ_NOBLOCK))
        {
            auto rpl = std::string(static_cast<char*>(msg.data()), msg.size());
            std::cout << "Recv returned true! " << rpl << "\n";
            int more;
            auto more_size = sizeof(more);
            sub.getsockopt(ZMQ_RCVMORE, &more, &more_size);
            while (more)
            {
                zmq::message_t moreMsg;
                sub.recv(&msg);
                std::string moreRpl = std::string(static_cast<char*>(moreMsg.data()), moreMsg.size());
                std::cout << "There's more! " << moreRpl << "Size is " << moreMsg.size() << "\n";
                sub.getsockopt(ZMQ_RCVMORE, &more, &more_size);
            }
        }
        else
            std::cout << "Recv returned false! " << zmq_strerror(zmq_errno()) << "\n";
    }
}

输出

Recv returned true! ragefire.bob
There's more! Size is 0

为了完整性,我的NetMQ子可以读取两个帧

static void Main()
{
    SubscriberSocket sub = new SubscriberSocket("tcp://localhost:8845");
    sub.SubscribeToAnyTopic();
    while (true)
    {
        NetMQMessage msg = sub.ReceiveMultipartMessage();
        Console.WriteLine($"Received! {Encoding.ASCII.GetString(msg.First.Buffer)}");
        Console.WriteLine($"Received! {Encoding.ASCII.GetString(msg[1].Buffer)}");
    }
}

1 个答案:

答案 0 :(得分:2)

您对 for (int j = 0; j < 100; j++) { fprintf(bp, "%d%c", s[i + j], (j == 99) ? '\n' : '\t'); } 的初次调用正在 sub.recv() 中收到消息,这很好。

您之后对&msg的来电也会收到sub.recv(),但您正在报告&msg。如果你真的想留下第二个moreMsg,那就去做

message_t