CServer.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include "../pch/pch.h"
  3. #include "CClientSession.h"
  4. using boost::asio::ip::tcp;
  5. class CClientMessage
  6. {
  7. public:
  8. int msg_type; //消息类型 0:新的外卖订单
  9. std::string timestamp;
  10. std::string m_username;
  11. std::string m_order_id;
  12. std::string m_order_no;
  13. std::string toJson()
  14. {
  15. rapidjson::Document doc;
  16. doc.SetObject();
  17. rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); //获取分配器
  18. doc.AddMember("msg_type", msg_type, allocator);
  19. doc.AddMember("timestamp", rapidjson::StringRef(timestamp.c_str(), timestamp.size()), allocator);
  20. doc.AddMember("username", rapidjson::StringRef(m_username.c_str(), m_username.size()), allocator);
  21. doc.AddMember("order_id", rapidjson::StringRef(m_order_id.c_str(), m_order_id.size()), allocator);
  22. doc.AddMember("order_no", rapidjson::StringRef(m_order_no.c_str(), m_order_no.size()), allocator);
  23. rapidjson::StringBuffer buffer;
  24. rapidjson::Writer<StringBuffer> writer(buffer);
  25. doc.Accept(writer);
  26. return buffer.GetString();
  27. }
  28. };
  29. class CServer
  30. {
  31. public:
  32. CServer()
  33. {
  34. }
  35. ~CServer()
  36. {
  37. delete acceptor_;
  38. }
  39. void Init();
  40. void BindUsername(std::string username, CClientSession* session);
  41. void DeleteClient(std::string username);
  42. private:
  43. void start_aliyun_mns();
  44. void start_accept();
  45. void handle_accept(CClientSession* new_session,
  46. const boost::system::error_code& error);
  47. //开启线程,监听接口层的消息
  48. void ReceiveMNSMessage();
  49. //开启线程,专门负责把消息发给客户端
  50. void SendMessageToClient();
  51. boost::asio::io_context io_context_;
  52. tcp::acceptor* acceptor_;
  53. //给客户端发送消息的队列
  54. std::queue<CClientMessage> m_message_queue;
  55. std::mutex m_queue_mutex;
  56. std::map<std::string, CClientSession*> m_clients_map;
  57. std::mutex m_map_mutex;
  58. int m_port;
  59. int m_nClientCount = 0;
  60. };