#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 = server_->Accept(); if (!cli) { return; } wxString tmp("Nihao"); cli->Write(tmp.c_str(), tmp.size()); } }