#include "server-core.h" // https://wizardforcel.gitbooks.io/wxwidgets-book/content/133.html CServerCore::CServerCore() { } CServerCore::~CServerCore() { } bool CServerCore::Init(const wxString& ip, unsigned short port) { wxIPV4address addr; addr.Service(port); server_ = std::make_unique(addr, wxSOCKET_NOWAIT); if (!server_->IsOk()) { return false; } server_id_ = wxNewId(); server_->SetEventHandler(*this, server_id_); server_->SetNotify(wxSOCKET_CONNECTION_FLAG); // 1. 设置监听的事件类型 server_->Notify(true); // 2. 启用事件通知 Bind(wxEVT_SOCKET, &CServerCore::OnServerEvent, this, server_id_); return true; } int CServerCore::Run() { wxEventLoop loop; return loop.Run(); } void CServerCore::OnServerEvent(wxSocketEvent& event) { if (event.GetSocketEvent() == wxSOCKET_CONNECTION) { auto* cli_ptr = server_->Accept(true); if (!cli_ptr) { return; } std::shared_ptr cli(cli_ptr, [](wxSocketBase* ptr) { ptr->Destroy(); }); wxIPV4address peer_addr; wxString id; if (cli->GetPeer(peer_addr)) { id.append(peer_addr.IPAddress()); id.append(":"); id.append(std::to_string(peer_addr.Service())); wxLogMessage("New connection from %s", id); } bool can = false; { std::unique_lock lock(cli_mut_); if (client_cache_.size() >= 100) { can = false; cli->Close(); } else { auto cache = std::make_shared(); cache->socket = cli; cache->last_recv_time = std::chrono::high_resolution_clock::now(); auto now = wxDateTime::Now(); cache->online_time = wxString::Format("%s.%03ld", now.Format("%Y-%m-%d %H:%M:%S"), now.GetMillisecond()); client_cache_.emplace(id, cache); can = true; } } if (!can) { std::this_thread::sleep_for(std::chrono::minutes(1)); } else { client_thread_.emplace(id, std::thread(&CServerCore::th_client_thread, this, cli, id)); } } } void CServerCore::th_client_thread(const std::shared_ptr& socket, const wxString& id) { }