zeromq发布pub和订阅sub

pub

#include "stdafx.h"

#include
#include


#include
#include
#include


using namespace std;


int main()
{
printf("Hello world!\n");


void* context = zmq_ctx_new();///创建一个新的环境
assert(context != NULL);


int ret = zmq_ctx_set(context, ZMQ_MAX_SOCKETS, 1);/// 在该环境中最大只允许一个socket存在
assert(ret == 0);


void* publisher = zmq_socket(context, ZMQ_PUB);/// 创建一个发布者
assert(publisher != NULL);


ret = zmq_bind(publisher, "tcp://192.168.1.128:8888");/// 绑定该发布到TCP通信
assert(ret == 0);


int i = 0; 
while (1)
{

std::string str;
str = "Hi,I'm server";
int n = str.size();
char buff[20];
memset(buff, 0, 20);
sprintf_s(buff, "Hi,I'm server %d\n", i);
n = str.size();
//ret = zmq_send(publisher, buff, 20, 0);/// 发送消息
  //assert(ret == 7);
printf("%s\n", buff);
Sleep(10);
i++;
}


printf("1\n");


return 0;

}


sub

#include "stdafx.h"
#include
#include
//#include
#include
#include


int main()
{
printf("Hello world!\n");


void* context = zmq_ctx_new();/// 创建一个新的环境
assert(context != NULL);


int ret = zmq_ctx_set(context, ZMQ_MAX_SOCKETS, 1);/// 该环境中只允许有一个socket的存在
assert(ret == 0);


void* subscriber = zmq_socket(context, ZMQ_SUB);/// 创建一个订阅者
assert(subscriber != NULL);


ret = zmq_connect(subscriber, "tcp://192.168.1.128:8888");/// 连接到服务器
assert(ret == 0);


ret = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);/// 必须添加该语句对消息滤波,否则接受不到消息
assert(ret == 0);


char buf[20];/// 消息缓冲区
while (1)
{
ret = zmq_recv(subscriber, buf, 20, ZMQ_DONTWAIT);/// 接收消息,非堵塞式
if (ret != -1)/// 打印消息
{
buf[ret - 1] = '\0';
printf("sub:%s\n", buf);
}
Sleep(1);
}






return 0;
}



你可能感兴趣的:(zeromq)