SHARE
TWEET

req2router.cpp

Riskybiz Aug 23rd, 2014 159 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. / req4router.cpp : Defines the entry point for the console application.
  2. //
  3. #include <string>
  4. #include "zmq2.h"
  5. #include "boost\lexical_cast.hpp"
  6. #include "boost\bind\bind.hpp"
  7. #include "boost\thread\thread.hpp"
  8.  
  9. const char* SK_ADDR_CLI = "tcp://localhost:5380";
  10. const char* SK_ADDR_SRV = "tcp://*:5380";
  11.  
  12. boost::mutex mio;
  13. void dumpId(const char* tag, const char* msg)
  14. {
  15.     boost::lock_guard<boost::mutex> lock(mio);
  16.     std::string id = boost::lexical_cast<std::string>(boost::this_thread::get_id());
  17.  
  18.     std::cout << id << ' ' << tag << ' ' << msg << std::endl;
  19. }
  20.  
  21. void req4router()
  22. {
  23.    
  24.         dumpId("REQ startup", SK_ADDR_CLI);
  25.     zmq::context_t context(1);
  26.      
  27.     zmq::Socket skReq(context, ZMQ_REQ); // 1
  28.     skReq.connect(SK_ADDR_CLI); // 2
  29.     dumpId("REQ CLI on", SK_ADDR_CLI);
  30.  
  31.     std::string id = boost::lexical_cast<std::string>(boost::this_thread::get_id()); // 3
  32.     skReq.send(id); // 4
  33.     std::string msg = skReq.recvAsString();
  34.     dumpId(msg.c_str(), SK_ADDR_CLI);
  35. }
  36.  
  37. void router(int nReq)
  38. {
  39.     dumpId("ROUTER startup", SK_ADDR_SRV);
  40.     zmq::context_t context(1);
  41.  
  42.     zmq::Socket skRouter(context, ZMQ_ROUTER); // 1
  43.     skRouter.bind(SK_ADDR_SRV);
  44.     dumpId("ROUTER SRV on", SK_ADDR_SRV);
  45.  
  46.     std::vector<zmq::Frames> msgs; // 2
  47.     for(int i = 0; i < nReq; ++i)
  48.     {
  49.         msgs.push_back(skRouter.blockingRecv(3)); // 3
  50.     }
  51.     dumpId("all received", SK_ADDR_SRV);
  52.  
  53.     std::for_each(msgs.begin(), msgs.end(), [&skRouter](zmq::Frames& frames)
  54.     {
  55.         skRouter.send(frames); // 4
  56.     });
  57.  
  58.     dumpId("ROUTER done", SK_ADDR_SRV);
  59. }
  60.  
  61. int main(int argc, char* argv[])
  62. {
  63.         int nReq = atoi(argv[1]);
  64.         boost::thread_group threads;
  65. for(int i = 0; i < nReq; ++i) // 1
  66.     threads.create_thread(req4router); // 2
  67. threads.create_thread(std::bind(router, nReq)); // 3
  68. threads.join_all();
  69. return 0;
  70. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top