Skip to content

Instantly share code, notes, and snippets.

@vpaladino778
Last active February 19, 2020 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vpaladino778/00864aeeba360d56d82e43d2d8904ec1 to your computer and use it in GitHub Desktop.
Save vpaladino778/00864aeeba360d56d82e43d2d8904ec1 to your computer and use it in GitHub Desktop.
ZeroMQ Client/Server - ROUTER/DEALER Minimal Example
#include <iostream>
#include <zmq.hpp>
#include <string>
#include <thread>
#include <chrono>
int main() {
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_ROUTER);
socket.bind("tcp://*:5555");
getchar();
try {
// Send JobRequest to camera to run
zmq::message_t request (10);
memcpy (request.data (), "JobRequest", 10);
std::cout << "Router: Sending JobRequest " << std::endl;
// Set the address, then the empty delimiter and then the request itself
socket.send("A", ZMQ_SNDMORE);
socket.send(zmq::message_t(), ZMQ_SNDMORE);
socket.send(request);
// Receive the reply from the camera
std::cout << "Router: Waiting for reply from camera " << std::endl;
zmq::message_t replyID(0);
zmq::message_t reply(0);
socket.recv(&replyID);
socket.recv(&reply);
std::cout << "Router: Received " << std::string(static_cast<char*>(reply.data()), reply.size()) << std::endl;
} catch (std::exception e) {
std::cout << "Router Error: " << e.what();
}
std::this_thread::sleep_for(std::chrono::seconds(1));
socket.setsockopt(ZMQ_LINGER, 0);
socket.close();
context.close();
}
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <thread>
int main (void)
{
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_DEALER);
std::cout << "Dealer: Connecting to RunJob server… \n";
socket.setsockopt(ZMQ_IDENTITY, "A", 1);
socket.connect ("tcp://localhost:5555");
while(1) {
try {
// Wait for next request from client
std::cout << "Dealer: Waiting for request" << std::endl;
zmq::message_t request(0);
// Receive request
socket.recv(&request);
std::cout << "Dealer: Received request" << std::endl;
std::cout << std::string(static_cast<char*>(request.data()),request.size()) << std::endl;
// Do some processing to the request here
// Send reply back to client
std::string string= "JobCompleted";
zmq::message_t message(string.size());
memcpy (message.data(), string.data(), string.size());
std::cout << "Router: Sending" << std::endl;
// ZMQ_SNDMORE - "Specifies that the message being sent is a multi-part message, and that further message parts are to follow"
socket.send(zmq::message_t(), ZMQ_SNDMORE);
socket.send(message);
}catch (std::exception e) {
std::cout << "Router Error: " << e.what();
}
}
// Used to set various 0MQ Socket Settings
// ZMQ_Linger - Set linger period for socket shutdown
socket.setsockopt(ZMQ_LINGER, 0);
socket.close();
context.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment