Advertisement
Guest User

Untitled

a guest
Aug 27th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. // g++ -std=c++11 -o pub_sub pub_sub.cpp -lzmq -lpthread
  2.  
  3. #include <iostream>
  4. #include <thread>
  5. #include <zmq.hpp>
  6.  
  7. std::string address("tcp://127.0.0.1:5566");
  8. zmq::context_t ctx;
  9.  
  10. void subscriber(void)
  11. {
  12.  
  13.     zmq::socket_t socket(ctx, ZMQ_SUB);
  14.  
  15.     int timeout(5000);
  16.     socket.setsockopt(ZMQ_RCVTIMEO, &timeout, sizeof(timeout));
  17.     socket.setsockopt(ZMQ_SUBSCRIBE, nullptr, 0);
  18.  
  19.     socket.bind(address);
  20.  
  21.     zmq::message_t msg;
  22.  
  23.     std::cout << "Wait for message." << std::endl;
  24.     if (socket.recv(&msg)) {
  25.         std::cout << "Got message." << std::endl;
  26.     }
  27.     else {
  28.         std::cerr << "Timeout waiting for message." << std::endl;
  29.     }
  30. }
  31.  
  32. int main ()
  33. {
  34.     std::thread sub(subscriber);
  35.  
  36.     // allow subscriber to bind() and recv()
  37.     std::this_thread::sleep_for(std::chrono::milliseconds(1));
  38.  
  39.     zmq::socket_t socket(ctx, ZMQ_PUB);
  40.     socket.connect(address);
  41.  
  42.     // no message is received if this sleep is removed
  43.     std::this_thread::sleep_for(std::chrono::milliseconds(1));
  44.  
  45.     zmq::message_t msg(0);
  46.     if (socket.send(msg)) {
  47.         std::cout << "Sent message." << std::endl;
  48.     }
  49.     else {
  50.         std::cerr << "Failed to send message." << std::endl;
  51.     }
  52.  
  53.     sub.join();
  54.  
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement