zeromq / libzmq

ZeroMQ core engine in C++, implements ZMTP/3.1
https://www.zeromq.org
Mozilla Public License 2.0
9.75k stars 2.36k forks source link

Is this possible to make zmq_proxy one-directional? #4209

Open xakod opened 3 years ago

xakod commented 3 years ago

Is this possible to make zmq_proxy one-directional or smth like this? For example i wanna use some kind of role delegation on backend (https://i.stack.imgur.com/6ZsbI.png) so i wanna proxy pass mesagges from frontend to subscriber backend and pass messages from publisher backend to frontend. I looked through docs and couldnt find smth similar.

ljluestc commented 8 months ago
#include <zmq.hpp>
#include <iostream>
#include <thread>

void proxy_frontend_to_backend(zmq::socket_t& frontend, zmq::socket_t& backend) {
    while (true) {
        zmq::message_t message;
        frontend.recv(message, zmq::recv_flags::none);
        backend.send(message, zmq::send_flags::none);
    }
}

void proxy_backend_to_frontend(zmq::socket_t& backend, zmq::socket_t& frontend) {
    while (true) {
        zmq::message_t message;
        backend.recv(message, zmq::recv_flags::none);
        frontend.send(message, zmq::send_flags::none);
    }
}

int main() {
    zmq::context_t context(1);

    // Frontend socket for clients
    zmq::socket_t frontend(context, ZMQ_ROUTER);
    frontend.bind("tcp://*:5555");

    // Backend socket for workers
    zmq::socket_t backend_sub(context, ZMQ_DEALER);
    backend_sub.bind("inproc://backend_sub");

    // Another backend socket for publishers
    zmq::socket_t backend_pub(context, ZMQ_DEALER);
    backend_pub.bind("inproc://backend_pub");

    // Thread for proxying from frontend to subscriber backend
    std::thread frontend_to_backend_thread([&]() {
        proxy_frontend_to_backend(frontend, backend_sub);
    });

    // Thread for proxying from publisher backend to frontend
    std::thread backend_to_frontend_thread([&]() {
        proxy_backend_to_frontend(backend_pub, frontend);
    });

    frontend_to_backend_thread.join();
    backend_to_frontend_thread.join();

    return 0;
}