Skip to content

Instantly share code, notes, and snippets.

@dkleissa
Created October 31, 2015 00:39
Show Gist options
  • Save dkleissa/31272fe043e733aff2c5 to your computer and use it in GitHub Desktop.
Save dkleissa/31272fe043e733aff2c5 to your computer and use it in GitHub Desktop.
super basic listening zmq server with polling
//
// Hello World server in C++ w/ polling
// Binds REP socket to tcp://*:5555
// Expects "Hello" from client, replies with "World"
//
#include <zmq.hpp>
#include <string>
#include <iostream>
#ifndef _WIN32
#include <unistd.h>
#else
#include <windows.h>
#define sleep(n) Sleep(n)
#endif
int main () {
// Prepare our context and socket
zmq::context_t context (1);
zmq::socket_t socket (context, ZMQ_REP);
socket.bind ("tcp://*:5555");
// Setup Polling - you can add multiple sockets here if you
// want to handle multiple sockets and then check them in serial below
zmq::pollitem_t items [] = {
{ socket, 0, ZMQ_POLLIN, 0 }
};
zmq::message_t request;
while (true) {
// Poll for incoming message event waiting 1sec.
// If you have a message to process this call returns immediately
// Timeout lets you do other things (like update a gui) and then go back to listening
// If you're doing this on the client side you might want to give up and throw and error message
zmq::poll (&items[0], 1, 1000);
if (items[0].revents & ZMQ_POLLIN) {
// Got a message! process it.
request.rebuild();
// Assuming single part message. If not you'd have to get all parts here
// zmq guarantees all parts arrive before flagging a message is there.
socket.recv (&request);
std::cout << "Received Hello" << std::endl;
// Do some 'work'
sleep(1);
// Send reply back to client
// You have to send a reply or the client will never be able to send another response
zmq::message_t reply (5);
memcpy ((void *) reply.data (), "World", 5);
socket.send (reply);
}
// Maybe do other things before going back to listening?
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment