ZeroMQ_04 发布订阅模式
Posted vczf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ZeroMQ_04 发布订阅模式相关的知识,希望对你有一定的参考价值。
简单来说,就是服务端不断发布消息,客户端订阅了就会收到消息。
下面我们看个简单的实力:
Server:
#include <stdlib.h> #include <zmq.h> #include <string.h> #include <unistd.h> #include <time.h> #define buffersize 4096 #define randof(num) (int) ((float) (num) * random () / (RAND_MAX + 1.0)) int main(int argc, char* argv[]) { // [0]创建对象 void* ctx = zmq_ctx_new(); void* publisher = zmq_socket(ctx, ZMQ_PUB); // [1]绑定到5566端口 zmq_bind(publisher, "tcp://*:5566"); // 初始化随机数生成器 srandom ((unsigned) time (NULL)); while (1) { int zipcode, temperature, relhumidity; zipcode = randof (100000); temperature = randof (215) - 80; relhumidity = randof (50) + 10; // Send message to all subscribers char update [20]; sprintf (update, "%05d %d %d", zipcode, temperature, relhumidity); printf("server send: %s ", update); //s_send (publisher, update); zmq_send (publisher, update, strlen (update), 0); sleep(1); } zmq_close(publisher); zmq_ctx_destroy(ctx); return 0; }
Client:
#include <stdlib.h> #include <zmq.h> #include <string.h> #include <unistd.h> #include <time.h> #include <assert.h> static char *s_recv (void *socket) { char buffer [256]; int size = zmq_recv (socket, buffer, 255, 0); if (size == -1) return NULL; buffer[size] = ‘