2025-03-31 20:18:54 +08:00
|
|
|
#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<wxSocketServer>(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) {
|
2025-03-31 22:51:47 +08:00
|
|
|
auto* cli_ptr = server_->Accept(true);
|
|
|
|
if (!cli_ptr) {
|
2025-03-31 20:18:54 +08:00
|
|
|
return;
|
|
|
|
}
|
2025-03-31 22:51:47 +08:00
|
|
|
std::shared_ptr<wxSocketBase> 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<std::shared_mutex> lock(cli_mut_);
|
|
|
|
if (client_cache_.size() >= 100) {
|
|
|
|
can = false;
|
|
|
|
cli->Close();
|
|
|
|
} else {
|
|
|
|
auto cache = std::make_shared<ClientCache>();
|
|
|
|
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));
|
|
|
|
}
|
2025-03-31 20:18:54 +08:00
|
|
|
}
|
|
|
|
}
|
2025-03-31 22:51:47 +08:00
|
|
|
|
|
|
|
void CServerCore::th_client_thread(const std::shared_ptr<wxSocketBase>& socket, const wxString& id)
|
|
|
|
{
|
|
|
|
}
|