ZMQ pubsub example
unknown
c_cpp
2 years ago
1.5 kB
7
Indexable
//pub.cpp
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>
int main() {
// Prepare the context and publisher socket
zmq::context_t context(1);
zmq::socket_t publisher(context, zmq::socket_type::pub);
// Bind the socket to an endpoint
publisher.bind("tcp://*:5556");
while (true) {
// Create a message
std::string msg = "Hello, world!";
zmq::message_t message(msg.size());
memcpy(message.data(), msg.data(), msg.size());
// Send the message
std::cout << "Sending message: " << msg << std::endl;
publisher.send(message, zmq::send_flags::none);
// Sleep for a second before sending the next message
sleep(1);
}
return 0;
}
// sub.cpp
#include <zmq.hpp>
#include <string>
#include <iostream>
int main() {
// Prepare the context and subscriber socket
zmq::context_t context(1);
zmq::socket_t subscriber(context, zmq::socket_type::sub);
// Connect to the publisher
subscriber.connect("tcp://localhost:5556");
// Subscribe to all messages
subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);
while (true) {
zmq::message_t message;
// Receive the message
subscriber.recv(message, zmq::recv_flags::none);
std::string msg_str(static_cast<char*>(message.data()), message.size());
std::cout << "Received message: " << msg_str << std::endl;
}
return 0;
}
Editor is loading...
Leave a Comment