use*_*490 3 c ubuntu tcp localhost zeromq
I have written a simple PUB/SUB program in zmq which is not working. In server.c, all I am doing is binding server to specific socket and then broadcasting a message "Hi!, Similarly, in client.c, I am receving the sent string and printing it but it always skips the loop. When I run client it does not receive any message from server.c. What could possibly be wrong?
//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;
}
Run Code Online (Sandbox Code Playgroud)
SUB 一方必须“订阅”某些东西只需添加使用zmq_setsockopt( subscriber, ZMQ_SUBSCRIBE, "", 0 )after .connect(), 将其设置为订阅过滤器,使其成为默认值 < *nothing* >以外的任何内容,这会导致不通过 SUB 端过滤器传递任何内容(直到更改此设置)。
有关详细信息,请查看有关PUB/SUB行为和.setsockopt()的 ZeroMQ 文档。
| 归档时间: |
|
| 查看次数: |
5181 次 |
| 最近记录: |