Zmq req/rep example

mail@pastecode.io avatar
unknown
c_cpp
25 days ago
2.0 kB
2
Indexable
Never
// server.cpp
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>

int main() {
    // Prepare the context and socket
    zmq::context_t context(1);
    zmq::socket_t socket(context, zmq::socket_type::rep);

    // Bind the socket to an endpoint
    socket.bind("tcp://*:5555");

    while (true) {
        zmq::message_t request;

        // Wait for the next request from client
        socket.recv(request, zmq::recv_flags::none);
        std::string request_str(static_cast<char*>(request.data()), request.size());
        std::cout << "Received request: " << request_str << std::endl;

        // Simulate work
        sleep(1);

        // Send reply back to client
        std::string reply_str = "World";
        zmq::message_t reply(reply_str.size());
        memcpy(reply.data(), reply_str.data(), reply_str.size());
        socket.send(reply, zmq::send_flags::none);
    }

    return 0;
}
#client.cpp
#include <zmq.hpp>
#include <string>
#include <iostream>

int main() {
    // Prepare the context and socket
    zmq::context_t context(1);
    zmq::socket_t socket(context, zmq::socket_type::req);

    // Connect to the server
    socket.connect("tcp://localhost:5555");

    for (int request_nbr = 0; request_nbr < 10; ++request_nbr) {
        // Create and send request
        std::string request_str = "Hello";
        zmq::message_t request(request_str.size());
        memcpy(request.data(), request_str.data(), request_str.size());
        std::cout << "Sending request " << request_nbr << ": " << request_str << std::endl;
        socket.send(request, zmq::send_flags::none);

        // Wait for reply
        zmq::message_t reply;
        socket.recv(reply, zmq::recv_flags::none);
        std::string reply_str(static_cast<char*>(reply.data()), reply.size());
        std::cout << "Received reply " << request_nbr << ": " << reply_str << std::endl;
    }

    return 0;
}
Leave a Comment