#pragma once #include "../pch/pch.h" #include "CClientSession.h" using boost::asio::ip::tcp; class CClientMessage { public: int m_type; //消息类型 0:新的外卖订单 std::string m_username; std::string m_order_id; std::string m_order_no; std::string toJson() { rapidjson::Document doc; doc.SetObject(); rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); //获取分配器 doc.AddMember("type", m_type, allocator); doc.AddMember("username", rapidjson::StringRef(m_username.c_str(), m_username.size()), allocator); doc.AddMember("order_id", rapidjson::StringRef(m_order_id.c_str(), m_order_id.size()), allocator); doc.AddMember("order_no", rapidjson::StringRef(m_order_no.c_str(), m_order_no.size()), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); doc.Accept(writer); return buffer.GetString(); } }; class CServer { public: CServer(boost::asio::io_context& io_context, short port) : io_context_(io_context), acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) { start_accept(); start_aliyun_mns(); std::thread t(&CServer::SendMessageToClient, this); t.detach(); } void BindUsername(std::string username, CClientSession* session); private: void start_aliyun_mns(); void start_accept(); void handle_accept(CClientSession* new_session, const boost::system::error_code& error); //开启线程,监听接口层的消息 void ReceiveMNSMessage(); //开启线程,专门负责把消息发给客户端 void SendMessageToClient(); boost::asio::io_context& io_context_; tcp::acceptor acceptor_; std::queue m_message_queue; std::mutex m_queue_mutex; std::map m_clients_map; };