概述
一、一问一答模式
服务端代码:
// server.cpp
#include "./include/zmq.h"
#pragma comment(lib, "libzmq.lib")
int _tmain(int argc, _TCHAR* argv[])
{
void *context = zmq_ctx_new();
void *responder = zmq_socket(context, ZMQ_REP);
int rc = zmq_bind(responder, "tcp://*:5555");
assert(rc == 0);
while (1) {
char buffer[11] = { 0 };
zmq_recv(responder, buffer, 10, 0);
printf("Received: %sn", buffer);
zmq_send(responder, "World", 5, 0);
}
return 0;
}
客户端代码:
// client.cpp
#include "include/zmq.h"
#pragma comment(lib, "libzmq.lib")
int _tmain(int argc, _TCHAR* argv[])
{
printf("Connecting to hello world server…n");
void *context = zmq_ctx_new();
void *requester = zmq_socket(context, ZMQ_REQ);
zmq_connect(requester, "tcp://localhost:5555");
zmq_send(requester, "Hello", 5, 0);
char buffer[11] = { 0 };
zmq_recv(requester, buffer, 10, 0);
printf("Received: %sn", buffer);
zmq_close(requester);
zmq_ctx_destroy(context);
return 0;
}
二、 消息订阅模式
消息发布者代码:
// Publisher.cpp
int _tmain(int argc, _TCHAR* argv[])
{
void *context = zmq_ctx_new();
void *publisher = zmq_socket(context, ZMQ_PUB);
int rc = zmq_bind(publisher, "tcp://*:5556");
assert(rc == 0);
while (1) {
// Send timestamp to all subscribers
char timestamp[31] = { 0 };
sprintf(timestamp, "timestamp %ld", time(NULL));
int size = zmq_send(publisher, timestamp, 30, 0);
Sleep(5000);
}
zmq_close(publisher);
zmq_ctx_destroy(context);
return 0;
}
消息订阅者代码:
// Subscribe.cpp
int _tmain(int argc, _TCHAR* argv[])
{
void *context = zmq_ctx_new ();
void *subscriber = zmq_socket (context, ZMQ_SUB);
int rc = zmq_connect (subscriber, "tcp://localhost:5556");
assert (rc == 0);
char *filter = "timestamp ";
rc = zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE, filter, strlen (filter));
assert (rc == 0);
char buffer[256] = {0};
int size = zmq_recv (subscriber, buffer, 255, 0);
printf("Timestamp: %sn", buffer);
zmq_close (subscriber);
zmq_ctx_destroy (context);
return 0;
}
最后
以上就是机灵中心为你收集整理的ZeroMQ入门示例一、一问一答模式二、 消息订阅模式的全部内容,希望文章能够帮你解决ZeroMQ入门示例一、一问一答模式二、 消息订阅模式所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复