上一篇讲到zmq的安装及简单的请求-应答模式,本篇主要来看一下zmq的pub-sub代码如何实现。
发布-订阅模式的特点:
1.一个发布者可以被多个订阅者订阅,即发布者和订阅者是1:n的关系
2.当发布者数据内容发生变化时发布数据,所有订阅者均能及时收到数据。
发布者的代码:pub.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include "zmq.h"
int main()
{
void* context = zmq_ctx_new();
assert(context != NULL);
void* publisher = zmq_socket(context, ZMQ_PUB);
assert(publisher != NULL);
int ret = zmq_bind(publisher, "tcp://*:5555");
assert(ret == 0);
int i = 0;
while(1)
{
char szBuf[1024] = {0};
snprintf(szBuf, sizeof(szBuf), "server i=%d", i);
printf("pub ctx: server i = %d\n",i);
ret = zmq_send(publisher, szBuf, strlen(szBuf) + 1, 0);
i++;
sleep(1);
}
zmq_close (publisher);
zmq_ctx_destroy (context);
return 0;
}
订阅者的代码:sub.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include "zmq.h"
int main()
{
printf("Hello sub!\n");
void* context = zmq_ctx_new();
assert(context != NULL);
void* subscriber = zmq_socket(context, ZMQ_SUB);
assert(subscriber != NULL);
int ret = zmq_connect(subscriber, "tcp://localhost:5555");
assert(ret == 0);
ret = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);
assert(ret == 0);
while(1)
{
printf("enter while to sub ctx\n");
char szBuf[1024] = {0};
ret = zmq_recv(subscriber, szBuf, sizeof(szBuf) - 1, 0);
if (ret > 0)
{
printf("%s\n", szBuf);
}
}
zmq_close(subscriber);
zmq_ctx_destroy(context);
return 0;
}
特别注意:
1.我们在pub中bind,在sub中connect,在zmq的使用中无论是在pub还是sub中都可以bind,但是一般我们在pub中bind,在sub中connect 。反之sub端可能收不到消息
2.zmq_setsockopt – 设置zmq socket属性,sub端必须使用此方法,否则是收不到消息的。详细使用方法见官方文档:http://api.zeromq.org/3-2:zmq-setsockopt
3.pub端不能使用recv函数,sub端不能使用send函数
编译:
扫描二维码关注公众号,回复:
12466307 查看本文章

g++ -o sub sub.cpp -lzmq
g++ -o pub pub.cpp -lzmq
运行:先运行pub可能会使订阅者错过部分发布内容,要想订阅完整的内容需要先启动sub,我这里启动两个sub