zeromq / cppzmq

Header-only C++ binding for libzmq
http://www.zeromq.org
MIT License
1.93k stars 757 forks source link

Does not get any message with PUB SUB sockets. #587

Closed jakepu closed 1 year ago

jakepu commented 1 year ago

I am trying to use PUB and SUB sockets for my project but I cannot pass the messages between these two sockets. If I change the socket type to PUSH and PULL they work. Could anyone help me?

The publisher test code is the following block.

#include <zmq.hpp>
#include <string>
#include <iostream>
#include <stdio.h>

int main (int argc, char *argv[])
{
    zmq::context_t context (1);
    zmq::socket_t socket (context, zmq::socket_type::pub);
    int id = atoi(argv[1]);
    char addr[100];
    sprintf(addr, "tcp://127.0.0.1:5555");
    socket.bind (addr);
    zmq_sleep(1);
    printf("bind %s\n", addr);
    while (fgetc(stdin)) {
        zmq::message_t request (5);
        memcpy (request.data (), "Hello", 5);
        std::cout << "Sending Hello " << std::endl;
        socket.send (request, zmq::send_flags::none);
    }

    return 0;
}

The subscriber test code is the following block.

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

int main () {
    zmq::context_t context;
    zmq::socket_t socket (context, zmq::socket_type::sub);
    socket.connect("tcp://127.0.0.1:5555");

    while (1) {
        zmq::message_t request;
        socket.recv (request, zmq::recv_flags::none);
        std::cout << request.to_string() << std::endl;
    }

    return 0;
}
jakepu commented 1 year ago

I forget to add a filter on the SUB socket. socket.setsockopt(ZMQ_SUBSCRIBE, "", 0);