ZeroMQ Radio/Dish 不接收消息

ZeroMQ Radio/Dish does not receive messages


我正在尝试让 ZeroMQ(带有普通 C 的 libzmq)中的 Radio/Dish 模式工作。最终我想使用 UDP 多播,但我什至无法让 TCP 单播工作。以下最小示例对我不起作用。我尝试了官方指南中的 Pub/Sub 示例,我可以确认 ZeroMQ over TCP 通常可以在我的机器上运行,但不能 Radio/Dish。我错过了什么?

电台:

#define ZMQ_BUILD_DRAFT_API

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <zmq.h>

int main(int argc, char *argv[]) {
    if (argc < 3) {
        printf("Please provide topic and message.");
        return EXIT_FAILURE;
    }

    void *context = zmq_ctx_new();
    void *radio = zmq_socket(context, ZMQ_RADIO);
    if (zmq_connect(radio, "tcp://127.0.0.1:5556") != 0) {
        printf("Failed to connect sending socket.");
        return EXIT_FAILURE;
    }

    zmq_msg_t msg;
    if (zmq_msg_init_data(&msg, argv[2], strlen(argv[2]), NULL, NULL) != 0) {
        printf("Failed to init message for topic %s.", argv[1]);
        return EXIT_FAILURE;
    }
    if (zmq_msg_set_group(&msg, argv[1]) != 0) {
        printf("Failed to set topic %s.", argv[1]);
        return EXIT_FAILURE;
    }
    if (zmq_msg_send(&msg, radio, 0) == -1) {
        zmq_msg_close(&msg);
        printf("Failed to send message \"%s\" on topic %s.", argv[2], argv[1]);
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

菜肴:

#define ZMQ_BUILD_DRAFT_API

#include <stdlib.h>
#include <stdio.h>
#include <zmq.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Please provide a topic.");
        return EXIT_FAILURE;
    }

    void *context = zmq_ctx_new();
    void *dish = zmq_socket(context, ZMQ_DISH);
    if (zmq_bind(dish, "tcp://*:5556") != 0) {
        printf("Failed to bind listen socket.");
        return EXIT_FAILURE;
    }

    if (zmq_join(dish, argv[1]) != 0) {
        printf("Could not subscribe to %s.", argv[1]);
        return EXIT_FAILURE;
    }

    int bytesReceived;
    zmq_msg_t receiveMessage;

    zmq_msg_init(&receiveMessage);
    bytesReceived = zmq_msg_recv(&receiveMessage, dish, 0);
    if (bytesReceived == -1) {
        printf("Failed to receive message.");
    } else {
        printf("topic: %s, data: %s, size: %d", zmq_msg_group(&receiveMessage), (char *)zmq_msg_data(&receiveMessage), bytesReceived);
    }

    zmq_msg_close(&receiveMessage);

    return EXIT_SUCCESS;
}

运行:

dish.exe TV
radio.exe TV test_msg

碟子似乎在听,收音机也没有错误地工作,但碟子从来没有收到任何东西。两个可执行文件在同一台机器上 运行。 提前谢谢你。

所以我自己想出来了。问题出在 Radio/Publisher。程序不能在 zmq_msg_send 之后立即结束,否则将不会发送消息。我在返回之前添加了一个正确的 zmq_ctx_destroy(context) 并解决了问题。
根据文档 zmq_ctx_destroy(context) 在关闭之前等待待发送的消息。这似乎是问题所在。