Zeromq:使用zmq的PUB / SUB程序,没有消息交换

时间:2014-09-13 23:49:58

标签: c ubuntu tcp localhost zeromq

我在zmq中写了一个简单的PUB / SUB程序,但是没有用。在server.c中,我所做的只是将服务器绑定到特定套接字,然后广播消息"嗨!,同样,在client.c中,我收到发送的字符串并打印它但它总是跳过循环。当我运行客户端时,它不会收到来自server.c的任何消息。什么可能是错的?

//server.c
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

int main (void)
{
    //  Prepare our context and publisher
    void *context = zmq_ctx_new ();
    void *publisher = zmq_socket (context, ZMQ_PUB);
    zmq_bind (publisher, "tcp://127.0.0.1:3333");
    char *string = "Hi!";

    while (1) {
        //  Send message to all subscribers
        zmq_msg_t message;
        zmq_msg_init_size (&message, strlen (string));
        memcpy (zmq_msg_data (&message), string, strlen (string));
        int rc = zmq_msg_send (publisher, &message, 0);
        zmq_msg_close (&message);
    }

    zmq_close (publisher);
    zmq_term (context);
    return 0;
}




//client.c
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

int main (int argc, char *argv [])
{
    int rc;
    void *context = zmq_ctx_new ();

    //  Socket to talk to server
    printf ("Collecting updates from server...\n");
    void *subscriber = zmq_socket (context, ZMQ_SUB);

    rc = zmq_connect (subscriber, "tcp://127.0.0.1:3333");
    assert (rc == 0);

      while(1){

    // Receive message from server
      zmq_msg_t message;
      zmq_msg_init (&message);
      if(zmq_msg_recv (subscriber, &message, 0))
      continue;
      int size = zmq_msg_size (&message);
      char *string = malloc (size + 1);
      memcpy (string, zmq_msg_data (&message), size);
      zmq_msg_close (&message);
      string [size] = 0;
      printf("Message is: %s\n",string);
      }

    zmq_close (subscriber);
    zmq_term (context);
    return 0;
}

1 个答案:

答案 0 :(得分:3)

SUB方必须“订阅”某事

只需在zmq_setsockopt( subscriber, ZMQ_SUBSCRIBE, "", 0 )之后添加.connect(),即可将订阅过滤器设置为默认值&lt; * nothing * &gt;以外的任何其他内容,这导致没有通过SUB侧过滤器(直到此设置被更改)。

有关详细信息,请查看有关PUB / SUB行为和.setsockopt()的ZeroMQ文档。

相关问题