Last active
November 11, 2021 15:38
-
-
Save jstaursky/f71160d330830b5e016652517a1336f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ZMQ PUB SUB |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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