1.编译zeromq, 默认不启动PGM协议, 编译前需要在属性中打开PGM支持, 打开后需要提供openPgm的库和头文件
2.服务器端代码
1 #include "stdafx.h" 2 #include "zmq.h" 3 4 5 6 int _tmain(int argc, _TCHAR* argv[]) 7 { 8 int index = 0; 9 int count = -1; 10 char buf[128]; 11 //上下文 12 void *context = zmq_ctx_new(); 13 //服务器指定为发布者 14 void *socket = zmq_socket(context, ZMQ_PUB); 15 //连接组播地址, epgm协议写法官网上有详细说明, 这里不指定网络接口, 使用默认 16 int rc = zmq_connect(socket, "epgm://239.0.1.2:20480"); 17 if (rc != 0) 18 { 19 return -1; 20 } 21 while (1) { 22 memset(buf, 0, 128); 23 sprintf_s(buf, "%d -- SERVER MSG!", index++); 24 //发送消息 25 count = zmq_send(socket, buf, strlen(buf), 0); 26 printf("%s (%d)\r\n", buf, count); 27 Sleep(1000); 28 } 29 30 zmq_close(socket); 31 zmq_ctx_destroy(context); 32 return 0; 33 }
3. 客户端
1 #include "stdafx.h" 2 #include "zmq.h" 3 4 5 int _tmain(int argc, _TCHAR* argv[]) 6 { 7 int count = -1; 8 char buf[128]; 9 void *context = zmq_ctx_new(); 10 //角色为订阅者 11 void *socket = zmq_socket(context, ZMQ_SUB); 12 //设置订阅消息过滤, 不设置则无法收到任何消息, 这里接收所有消息 13 zmq_setsocketopt(socket, ZMQ_SUBSCRIBE, "", 0); 14 int rc = zmq_connect(socket, "epgm://239.0.1.2:20480"); 15 if (rc != 0) 16 { 17 return -1; 18 } 19 while (1) { 20 memset(buf, 0, 128); 21 count = zmq_recv(socket, buf, 128, 0); 22 if (get > 0) 23 { 24 printf("RECV: %s\r\n", buf); 25 } 26 else 27 { 28 printf("ERROR: %d\r\n", count); 29 } 30 } 31 32 zmq_close(socket); 33 zmq_ctx_destroy(context); 34 return 0; 35 }