RedZMQ.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // RedZMQ.h
  3. // rebolt
  4. //
  5. // Created by zhuge on 2022/11/7.
  6. // Red ZMQ的一层封装,屏蔽zmq的使用细节,继承相对应的类,然后设置对应的endpoint即可
  7. #ifndef RedZMQ_h
  8. #define RedZMQ_h
  9. #include <string>
  10. #include <functional>
  11. namespace red_zmq {
  12. /**
  13. 广播消息
  14. 例:
  15. class Editor : Pub {
  16. Editor(): Pub("tcp://:5555") {}
  17. }
  18. Editor()->pubMsg("{}");
  19. */
  20. class Pub {
  21. public:
  22. Pub(std::string endPoint);
  23. /**
  24. 广播信息,不会阻塞,还没有连接的sub收不到
  25. return 发送状态
  26. */
  27. int pubMsg(const char* sendMsg);
  28. private:
  29. std::string _endPoint;
  30. void *_context;
  31. void *_socket;
  32. void _bind();
  33. };
  34. /// 注: onMsg为接收消息的子线程
  35. class Sub {
  36. public:
  37. Sub(const std::string& endPoint, const std::function<void(const std::string&)>& handleMsgCb);
  38. private:
  39. std::string _endPoint;
  40. std::function<void(const std::string&)> _handleMsgCb;
  41. void *_context;
  42. void *_socket;
  43. void _connect();
  44. void _threadReceiveMsg();
  45. };
  46. class Req {
  47. public:
  48. Req(std::string endPoint);
  49. /**
  50. 发送信息,如果无rep,会阻塞!!!
  51. */
  52. std::string sendMsg(const char* sendMsg);
  53. private:
  54. std::string _endPoint;
  55. void *_context;
  56. void *_socket;
  57. void _connect();
  58. };
  59. /// 注: onMsg为接收消息的子线程
  60. class Rep {
  61. public:
  62. Rep(const std::string& endPoint, const std::function<std::string(const std::string&)>& handleMsgCb);
  63. private:
  64. std::string _endPoint;
  65. std::function<std::string(const std::string&)> _handleMsgCb;
  66. void *_context;
  67. void *_socket;
  68. void _bind();
  69. void _threadReceiveMsg();
  70. };
  71. };
  72. #endif /* RedZMQ_h */