一、使用C++ ZMQ 开发一个简单的例子
使用 REQ-REP 模型
服户端
//
// Created by yanuas on 19-5-27.
// 第一个简单程序, 客户端发送Hello, 服务端应答World
// 服务端
// TODO 第一个模型 - REP~REQ
//
#include <iostream>
#include <zmq.hpp>
using std::cout;
using std::endl;
using std::cin;
int main() {
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REP);
socket.bind("tcp://*:6557");
cout << "The server is starting." << endl;
while (true) {
zmq::message_t message;
// 等待来自客户端的下一个请求
// 阻塞到当前语句, 直到收到来自客户端的信息, 然后存入至message
socket.recv(&message);
cout << "Come from client." << endl;
// do some work
zmq_sleep(1);
// 发送信息给客户端[应答]
zmq::message_t reply(5);
memcpy(reply.data(), "World", 5);
socket.send(reply);
}
return 0;
}
客户端
//
// Created by yanuas on 19-5-27.
// 第一个简单程序, 客户端发送Hello, 服务端应答World
// 客户端
// TODO 第一个模型 - REP~REQ
//
#include <iostream>
#include <zmq.hpp>
using std::cout;
using std::endl;
using std::cin;
int main() {
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REQ);
socket.connect("tcp://localhost:6557");
cout << "The client is connect." << endl;
// Do 10 requests, waiting each time for a response
for (int l = 0; l < 10; l++) {
zmq::message_t request_msg(5);
memcpy(request_msg.data(), "Hello", 5);
cout << "第" << l << "次发送Hello!" << endl;
socket.send(request_msg);
// Get the reply
zmq::message_t recv_msg;
socket.recv(&recv_msg);
cout << "Receive 'World' " << l << "次" << endl;
}
return 0;
}
结果
The client is connect.
第0次发送Hello!
Receive 'World' 0次
第1次发送Hello!
Receive 'World' 1次
第2次发送Hello!
Receive 'World' 2次
......
Process finished with exit code 0