RUDataTransMgr.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // RUDataTransMgr.h
  3. // base_world_ios
  4. //
  5. // Created by ZhengSong on 2023/2/28.
  6. //
  7. #ifndef RUDataTransMgr_h
  8. #define RUDataTransMgr_h
  9. #include "RUDefine.h"
  10. #include "RedZMQ.h"
  11. NS_RU_BEGIN
  12. /**
  13. * Pub 和 Sub 是一对 (pub是发送, sub是接收)
  14. * Req 和 Rep 是一对 (req是发送, rep是接收)
  15. *
  16. * App_A 中可以放Pub 和 Rep
  17. * App_B 中可以放Sub 和 Req
  18. *
  19. * Req 发送消息会阻塞线程
  20. */
  21. class DataTransDelegate {
  22. public:
  23. ///处理从订阅者发送的消息
  24. virtual void handleReceiveMessageFromPub(const std::string& command, const std::string& data) {}
  25. ///处理请求-应答发送的消息
  26. virtual std::string handleReceiveMsgFromReq(const std::string& command, const std::string& data) {return "";}
  27. };
  28. class DataTransMgr {
  29. public:
  30. static DataTransMgr* getInstance();
  31. /// socket通信(Sub-Req),发送信息会阻塞
  32. /// @param sender 发送地址,例如"tcp://localhost:5556"
  33. /// @param receiver 接收地址,例如tcp://localhost:5555"
  34. void connectSync(const std::string& sender, const std::string& receiver);
  35. /// socket通信(Pub-Rep),发送信息不会阻塞
  36. /// @param sender 发送地址,例如"tcp://*:5555"
  37. /// @param receiver 接收地址,例如"tcp://*:5556"
  38. void connectAsync(const std::string& sender, const std::string& receiver);
  39. /// 向订阅者发送消息
  40. /// @param command 消息类型
  41. /// @param data 消息内容
  42. void sendMsgToSubscriber(const std::string& command, const std::string& data);
  43. /// 请求消息并返回应答消息(阻塞直到返回应答消息)
  44. /// @param command 消息类型
  45. /// @param data 消息内容
  46. std::string requestMsg(const std::string& command, const std::string& data);
  47. ///设置代理
  48. void setDataTransDelegate(DataTransDelegate* delegate);
  49. private:
  50. DataTransMgr();
  51. ~DataTransMgr();
  52. //处理远端发送的消息
  53. void _handlePubMessage(const std::string& msg);
  54. std::string _handleReqMessage(const std::string& msg);
  55. private:
  56. red_zmq::Req* _zmqReq = nullptr;
  57. red_zmq::Sub* _zmqSub = nullptr;
  58. red_zmq::Pub* _zmqPub = nullptr;
  59. red_zmq::Rep* _zmqRep = nullptr;
  60. DataTransDelegate* _dataTransDelegate = nullptr;
  61. };
  62. NS_RU_END
  63. #endif /* RUDataTransMgr_h */