我正在尝试使用&#lib; libczmq'编写一个简单的程序来演示发布者/订阅者通信。虽然我可以通过' zmsg_send'来发送消息。 api(或者根据其返回值推测),我无法通过' zmsg_recv'来接收消息。 (阻塞)API,它可能无法接收消息。
#include "czmq.h"
int main (void)
{
int rc;
const char *ipc_file="ipc://tmp.socket";
const char *str = "Hello World!!!";
/*****************************************/
/* Creating and binding publisher Socket */
/*****************************************/
zsock_t *pub_sock = zsock_new(ZMQ_PUB);
assert(pub_sock!=NULL);
rc = zsock_bind(pub_sock, ipc_file, NULL);
assert(rc==0);
/**************************************************/
/* Creating and connecting with Subscriber Socket */
/**************************************************/
zsock_t *sub_sock = zsock_new(ZMQ_SUB);
assert(sub_sock);
rc = zsock_connect(sub_sock, ipc_file, NULL);
assert(rc==0);
/***************************************/
/* Creating messager & Frame instances */
/* and sending message */
/***************************************/
zmsg_t *msg = zmsg_new ();
assert(msg!=NULL);
zframe_t *frame = zframe_new (str, strlen(str));
assert(frame!=NULL);
zmsg_prepend(msg, &frame);
printf("PUB : frame_count = %u, content_size = %d, msg_ptr = %p\n",
zmsg_size (msg), zmsg_content_size(msg), msg);
rc = zmsg_send(&msg, pub_sock);
assert (rc == 0);
printf("PUB : Message send successfully...\n");
/********************************/
/* Subscriber receiving message */
/********************************/
printf("SUB : Reading message...\n");
msg = zmsg_recv(sub_sock);
assert(msg!=NULL);
printf("SUB : frame_count = %u, content_size = %d, msg_ptr = %p\n",
zmsg_size (msg), zmsg_content_size(msg), msg);
frame = zmsg_pop(msg);
assert(frame!=NULL);
printf("SUB : received in frame = \"%s\"\n", zframe_data (frame));
zmsg_destroy (&msg);
zframe_destroy (&frame);
zsock_destroy (&sub_sock);
zsock_destroy (&pub_sock);
return 0;
}
以下是我构建和执行应用程序的方法。
user@debian:~/progs/czmq$ make
cc -Iczmq/include -ggdb -c -o pub-sub-test.o pub-sub-test.c
gcc -L./czmq/src/.libs -lzmq -lczmq -lpthread pub-sub-test.o -o ../pub-sub-test
user@debian:~/progs/czmq$ ../pub-sub-test
PUB : frame_count = 1, content_size = 14, msg_ptr = 0x1653b10
PUB : Message send successfully...
SUB : Reading message...
'消息'订阅者永远不会阅读,请告诉我这里缺少的内容。
答案 0 :(得分:0)
默认情况下,SUB套接字上没有订阅。尝试使用订阅的变体:
zsock_t* zsock_new_sub (const char *endpoints, const char *subscribe)
或者在:
之后创建订阅zsock_set_subscribe (void *zsock, const char *subscribe);
空字符串订阅所有内容。
答案 1 :(得分:0)
上述程序存在两个问题。
解决方案: