zeromq / cppzmq

Header-only C++ binding for libzmq

Home Page:http://www.zeromq.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Multiple publisher and single subscriber pattern failed, works in python publisher

simsicon opened this issue · comments

I have a scenario that a single subscriber receives messages from multi publishers to gather informations.

To demo this problem, consider the following sub:

#include <iostream>
#include "zmq.hpp"


int main(int argc, char **argv)
{
    std::cout << "Subscriber..." << std::endl;

    zmq::context_t context (1);
    zmq::socket_t subscriber (context, ZMQ_SUB);

    subscriber.bind("ipc:///tmp/pub-sub");

    subscriber.set(zmq::sockopt::subscribe, "");

    while (true) {
        zmq::message_t message;
        auto res = subscriber.recv(message);

        std::string message_str(static_cast<char*>(message.data()), message.size());

        std::cout << "Received message: " << message_str << std::endl;
    }

    return 0;
}

Note that bind is used here because I have read that bind should be used to the single endpoint.

the pub:

#include <iostream>
#include <thread>
#include <chrono>
#include "zmq.hpp"


int main(int argc, char **argv)
{
    std::cout << "Publisher..." << std::endl;

    zmq::context_t context (1);
    zmq::socket_t publisher (context, ZMQ_PUB);

    publisher.connect("ipc:///tmp/pub-sub");

    while (true)
    {
        auto res = publisher.send(zmq::buffer(std::string(argv[1]) + " hi"), zmq::send_flags::none);
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << res.value() << std::endl;
    }

    return 0;
}

Connect is used in pub.

With the above code, I will not receive any messages from publishers.

But if I change the pub code to python, it will work

import sys
import time
import zmq

context = zmq.Context()
publisher = context.socket(zmq.PUB)
publisher.connect("ipc:///tmp/pub-sub")

while True:
    publisher.send(f"{sys.argv[1]} hi".encode())
    time.sleep(1)

Sub will receive from all of pubs.

Could you please identify this as a bug?

It seems that the socket is still connecting when the first message publishing.