[一] ZMQ-c++ Simple example

1、使用C++ ZMQ 開發一個簡單的例子

使用 REQ-REP 模型ios


服戶端

//
// 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
相關文章
相關標籤/搜索