| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- #pragma once
- #include "../pch/pch.h"
- #include "CClientSession.h"
- using boost::asio::ip::tcp;
- class CClientMessage
- {
- public:
- int msg_type; //消息类型 0:新的外卖订单
- std::string timestamp;
- 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("msg_type", msg_type, allocator);
- doc.AddMember("timestamp", rapidjson::StringRef(timestamp.c_str(), timestamp.size()), 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<StringBuffer> writer(buffer);
- doc.Accept(writer);
- return buffer.GetString();
- }
- };
- class CServer
- {
- public:
- CServer()
- {
- }
- ~CServer()
- {
- delete acceptor_;
- }
- void Init();
- void BindUsername(std::string username, CClientSession* session);
- void DeleteClient(std::string username);
- 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<CClientMessage> m_message_queue;
- std::mutex m_queue_mutex;
- std::map<std::string, CClientSession*> m_clients_map;
- std::mutex m_map_mutex;
- int m_port;
- int m_nClientCount = 0;
- };
|