Skip to content

Instantly share code, notes, and snippets.

@hmartiro
Created December 10, 2014 11:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hmartiro/df1eb214f77f549b3691 to your computer and use it in GitHub Desktop.
Save hmartiro/df1eb214f77f549b3691 to your computer and use it in GitHub Desktop.
ZeroMQ pub/sub usage and latency timing for C++11
/**
* Example of ZeroMQ pub/sub usage for C++11.
*/
#include <zmqpp/zmqpp.hpp>
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
static const string PUBLISH_ENDPOINT = "tcp://*:4242";
int main(int argc, char *argv[]) {
// Create a publisher socket
zmqpp::context context;
zmqpp::socket_type type = zmqpp::socket_type::publish;
zmqpp::socket socket (context, type);
// Open the connection
cout << "Binding to " << PUBLISH_ENDPOINT << "..." << endl;
socket.bind(PUBLISH_ENDPOINT);
// Pause to connect
this_thread::sleep_for(chrono::milliseconds(1000));
while(true) {
// Current time in ms
unsigned long ms = chrono::system_clock::now().time_since_epoch() /
chrono::milliseconds(1);
string text = "Hello at " + to_string(ms);
// Create a message and feed data into it
zmqpp::message message;
message << text;
// Send it off to any subscribers
socket.send(message);
cout << "[SENT] at " << ms << ": " << text << endl;
this_thread::sleep_for(chrono::microseconds(1000));
}
// Unreachable, but for good measure
socket.disconnect(PUBLISH_ENDPOINT);
return 0;
}
/**
* Example of ZeroMQ pub/sub usage for C++11.
*/
#include <zmqpp/zmqpp.hpp>
#include <iostream>
#include <chrono>
using namespace std;
static const string PUBLISHER_ENDPOINT = "tcp://localhost:4242";
int main(int argc, char *argv[]) {
// Create a subscriber socket
zmqpp::context context;
zmqpp::socket_type type = zmqpp::socket_type::subscribe;
zmqpp::socket socket(context, type);
// Subscribe to the default channel
socket.subscribe("");
// Connect to the publisher
cout << "Connecting to " << PUBLISHER_ENDPOINT << "..." << endl;
socket.connect(PUBLISHER_ENDPOINT);
while(true) {
// Receive (blocking call)
zmqpp::message message;
socket.receive(message);
// Read as a string
string text;
message >> text;
unsigned long ms = std::chrono::system_clock::now().time_since_epoch() /
std::chrono::milliseconds(1);
cout << "[RECV] at " << ms << ": \"" << text << "\"" << endl;
}
// Unreachable, but for good measure
socket.disconnect(PUBLISHER_ENDPOINT);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment