CServer.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 m_type; //消息类型 0:新的外卖订单
  9. std::string m_username;
  10. std::string m_order_id;
  11. std::string m_order_no;
  12. std::string toJson()
  13. {
  14. rapidjson::Document doc;
  15. doc.SetObject();
  16. rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); //获取分配器
  17. doc.AddMember("type", m_type, allocator);
  18. doc.AddMember("username", rapidjson::StringRef(m_username.c_str(), m_username.size()), allocator);
  19. doc.AddMember("order_id", rapidjson::StringRef(m_order_id.c_str(), m_order_id.size()), allocator);
  20. doc.AddMember("order_no", rapidjson::StringRef(m_order_no.c_str(), m_order_no.size()), allocator);
  21. rapidjson::StringBuffer buffer;
  22. rapidjson::Writer<StringBuffer> writer(buffer);
  23. doc.Accept(writer);
  24. return buffer.GetString();
  25. }
  26. };
  27. class CServer
  28. {
  29. public:
  30. CServer(boost::asio::io_context& io_context, short port)
  31. : io_context_(io_context),
  32. acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
  33. {
  34. start_accept();
  35. start_aliyun_mns();
  36. std::thread t(&CServer::SendMessageToClient, this);
  37. t.detach();
  38. }
  39. void BindUsername(std::string username, CClientSession* session);
  40. private:
  41. void start_aliyun_mns();
  42. void start_accept();
  43. void handle_accept(CClientSession* new_session,
  44. const boost::system::error_code& error);
  45. //开启线程,监听接口层的消息
  46. void ReceiveMNSMessage();
  47. //开启线程,专门负责把消息发给客户端
  48. void SendMessageToClient();
  49. boost::asio::io_context& io_context_;
  50. tcp::acceptor acceptor_;
  51. std::queue<CClientMessage> m_message_queue;
  52. std::mutex m_queue_mutex;
  53. std::map<std::string, CClientSession*> m_clients_map;
  54. };