我已经写了一个简单的zmq PUB/SUB程序,但它不能正常工作。在server.c中,我只是将服务器绑定到特定的套接字,然后广播一条消息“Hi!”。同样,在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;
}