Skip to content

Instantly share code, notes, and snippets.

@jstaursky
Last active November 11, 2021 15:38
Show Gist options
  • Save jstaursky/f71160d330830b5e016652517a1336f1 to your computer and use it in GitHub Desktop.
Save jstaursky/f71160d330830b5e016652517a1336f1 to your computer and use it in GitHub Desktop.
all:
g++ pub.cpp `pkg-config --cflags --libs libzmq` -o pub
g++ sub.cpp `pkg-config --cflags --libs libzmq` -o sub
clean:
rm pub sub
#include <zmq.hpp>
#include <iostream>
using namespace std;
static const string PUBLISH_ENDPOINT = "tcp://127.0.0.1:4321";
int main (int argc, char *argv[]) {
// Create a publisher socket
zmq::context_t context;
zmq::socket_t socket (context, zmq::socket_type::pub);
// Open the connection
socket.bind (PUBLISH_ENDPOINT);
while(true) {
string text = "Hello";
// Create a message and feed data into it
zmq::message_t message(text.size());
memcpy (message.data (), text.data (), text.size ());
socket.send(message, zmq::send_flags::dontwait);
}
// Unreachable, but for good measure
socket.disconnect (PUBLISH_ENDPOINT);
return 0;
}
#include <zmq.hpp>
#include <iostream>
using namespace std;
static const string PUBLISHER_ENDPOINT = "tcp://localhost:4321";
int main (int argc, char *argv[]) {
// Create a subscriber socket
zmq::context_t context;
zmq::socket_t socket (context, zmq::socket_type::sub);
// Subscribe to all messages
socket.setsockopt(ZMQ_SUBSCRIBE, "", 0);
// Connect to the publisher
socket.connect(PUBLISHER_ENDPOINT);
while(true) {
zmq::message_t message;
socket.recv (message, zmq::recv_flags::dontwait);
// Read as a string
string text = std::string (static_cast<char*>(message.data ()), message.size ());
if (!text.empty())
cout << "[RECV] #" << ": \"" << 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