这篇文章是第2篇的扩展
框架:
提供中间代码(XSUB-proxy-XSUB)。前、后端的代码可以参考第2篇文章,只是连接方式改成了connect而不是bind,所有要bind的endpoint都在中间代理中。
#include<zmq.h>
#include<iostream>
using std::endl;
using std::cout;
int main()
{
void* pContext = zmq_ctx_new();
void* pXsubSocket = zmq_socket(pContext, ZMQ_XSUB);
//定阅所有消息;
zmq_setsockopt(pXsubSocket, ZMQ_SUBSCRIBE, 0, 0);
int highWaterLevel = 2000;
//设置接收与发送的高水位;
zmq_setsockopt(pXsubSocket, ZMQ_RCVHWM, &highWaterLevel, sizeof(highWaterLevel));
zmq_setsockopt(pXsubSocket, ZMQ_SNDHWM, &highWaterLevel, sizeof(highWaterLevel));
zmq_bind(pXsubSocket, "tcp://*:6001"); //前端绑定;
void* pXpubSocket = zmq_socket(pContext, ZMQ_XPUB);
//设置接收与发送的高水位;
zmq_setsockopt(pXpubSocket, ZMQ_RCVHWM, &highWaterLevel, sizeof(highWaterLevel));
zmq_setsockopt(pXpubSocket, ZMQ_SNDHWM, &highWaterLevel, sizeof(highWaterLevel));
zmq_bind(pXpubSocket, "tcp://*:6002");//后端绑定;
cout << "start proxy..." << endl;
zmq_proxy(pXsubSocket, pXpubSocket, NULL); //循环代理工作;
zmq_close(pXpubSocket);
zmq_close(pXsubSocket);
zmq_ctx_destroy(pContext);
return 0;
}
结果: