Fix: make UDP and KCP clients stay online

Plain UDP gave every datagram a fresh context and destroyed it after
parsing, while the heartbeat handler posted that pointer to the UI thread,
so UpdateActiveWindow read freed memory. Login also stored that short-lived
context, so later heartbeats carried a zero client id and every UDP host
timed out.

The UDP server now owns one persistent context per client address and
dispatches every datagram through it: the receive buffer is cleared per
packet, the map is capped and idle addresses evicted, and Disconnect only
erases and marks the context so the last reference deletes it. COMMAND_BYE
no longer closes the shared receive socket, a failed receive re-posts
itself, and UDP previews are capped to thumbnail size.

The KCP client returned ikcp_send's 0 for a successful send, so the caller
resent login forever and never started heartbeats; it now reports the
accepted length, and a duplicate login re-sends MasterSettings.

Two follow-up fixes in the same area: ReleaseIoRef keeps fetch_sub paired
with exchange so a concurrent Disconnect cannot strand a marked context at
zero refs; UpdateUserEvent drops posted heartbeats while closing instead of
touching a context the UDP server may have destroyed. TCP behavior is
otherwise unchanged.

Verified: Debug build, UDP previews and heartbeats work, KCP logs in once
and reports its active window. Server link hits the known LNK1104 from the
running exe.

Co-Authored-By: Tencent Hunyuan Hy
This commit is contained in:
yuanyuanxiangandTencent Hunyuan Hy committed 2026-11-29 14:31:41 +01:00
1 parent d48f236385
commit 914553ab4e
8 files changed
+280 -30

No files matched your search

+102 -5
View File
@@ -85,6 +85,60 @@ void IOCPUDPServer::PostRecv()
}
}
std::string IOCPUDPServer::MakeKey(const sockaddr_in& addr)
{
char buf[64];
sprintf_s(buf, "%s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
return buf;
}
CONTEXT_UDP* IOCPUDPServer::FindOrCreateClient(const sockaddr_in& addr)
{
std::string key = MakeKey(addr);
std::lock_guard<std::mutex> lock(m_clientsMutex);
auto it = m_clients.find(key);
CONTEXT_UDP* ctx = (it != m_clients.end()) ? it->second : nullptr;
if (ctx == nullptr) {
// 和接收上下文共用上限,防止地址枚举把映射和内存撑爆
if ((int)m_clients.size() >= m_maxConn)
return nullptr;
ctx = new CONTEXT_UDP();
ctx->InitMember(m_socket, this);
ctx->clientAddr = addr;
ctx->addrLen = sizeof(sockaddr_in);
m_clients[key] = ctx;
}
// 在锁内加引用:避免和 Disconnect 的“移除 + 删除”交错,导致下发地址
// 之后再访问已释放的上下文。
ctx->IoRefCount.fetch_add(1);
return ctx;
}
void IOCPUDPServer::Disconnect(CONTEXT_OBJECT* ctx)
{
if (!ctx || ctx->GetProtocol() != "UDP")
return; // TCP/KCP 上下文不归本服务端管
CONTEXT_UDP* udp = static_cast<CONTEXT_UDP*>(ctx);
{
std::lock_guard<std::mutex> lock(m_clientsMutex);
auto it = m_clients.find(MakeKey(udp->clientAddr));
if (it == m_clients.end() || it->second != ctx)
return;
m_clients.erase(it);
// 先占一枚临时引用:保证在“置删除标记”之前不会有人把我们当成最后
// 一个释放者,删除动作只由下面的 ReleaseIoRef 或后续释放者完成。
ctx->IoRefCount.fetch_add(1);
}
// 不调用 m_offline:宿主列表的移除由对话框自己完成,再回调会重复提示下线。
// 也不等待引用归零:调用方(心跳超时/删除主机的 UI 线程)可能自己持有引用。
// 标记后交给最后一个释放引用的人销毁。
ctx->DeleteWhenIdle.store(true);
ctx->ReleaseIoRef(); // 本次函数不再触碰 ctx
}
void IOCPUDPServer::WorkerThread()
{
while (m_running) {
@@ -101,18 +155,52 @@ void IOCPUDPServer::WorkerThread()
delete ioCtx;
DelCount();
}
// 失败(典型是数据报大于 8KB 接收缓冲导致的 WSAEMSGSIZE)也要补投,
// 否则接收槽逐次减少,4 个之后服务端再也收不到任何 UDP 包。
if (m_running)
PostRecv();
continue;
}
if (!pOverlapped) continue;
IO_CONTEXT* ioCtx = CONTAINING_RECORD(pOverlapped, IO_CONTEXT, ol);
CONTEXT_UDP* ctx = ioCtx->pContext;
BOOL ret = ParseReceivedData(ctx, (PBYTE)ctx->szBuffer, bytes, m_notify);
if (999 != ret)
ctx->Destroy();
// 接收上下文只负责装缓冲和来源地址;真正参与分发的是按地址复用的
// 持久上下文(登录时存进宿主列表的就是它,心跳必须命中同一对象)。
CONTEXT_UDP* recvCtx = ioCtx->pContext;
CONTEXT_UDP* ctx = FindOrCreateClient(recvCtx->clientAddr);
if (ctx != nullptr) {
// 每个数据报是独立完整包;清掉上一包的残留,避免解析器把两包拼在
// 一起(持久上下文不像旧的“每包一个上下文”那样天然干净)。
ctx->InCompressedBuffer.ClearBuffer();
ParseReceivedData(ctx, (PBYTE)recvCtx->szBuffer, bytes, m_notify);
ctx->ReleaseIoRef(); // 若容器已标记删除且这是最后一枚引用,就地销毁
}
// 约每分钟清理一次长时间没有数据报的上下文,避免映射无限增长。
// 600s 远大于心跳超时(>=120s),被清理的都是早已从宿主列表移除的地址。
static time_t lastSweep = 0;
time_t now = time(0);
if (now - lastSweep >= 60) {
lastSweep = now;
std::vector<CONTEXT_UDP*> stale;
{
std::lock_guard<std::mutex> lock(m_clientsMutex);
for (auto& kv : m_clients) {
if (now - (time_t)kv.second->GetLastHeartbeat() > 600) {
kv.second->IoRefCount.fetch_add(1); // 保护指针,避免并发删除
stale.push_back(kv.second);
}
}
}
for (CONTEXT_UDP* c : stale) {
c->GetServer()->Disconnect(c); // 摘除映射并置删除标记(不等待)
c->ReleaseIoRef(); // 丢弃保护引用,必要时在此销毁
}
}
// 持久上下文不在这里释放:它由 m_clients 持有,主机下线时经
// Disconnect 释放。ioCtx 的析构只回收接收缓冲上下文。
// 释放
ioCtx->pContext = NULL;
delete ioCtx;
DelCount();
@@ -179,4 +267,13 @@ VOID IOCPUDPServer::Destroy()
SAFE_CLOSE_HANDLE(m_hIOCP);
m_hIOCP = NULL;
}
// 清理所有持久上下文
{
std::lock_guard<std::mutex> lock(m_clientsMutex);
for (auto& kv : m_clients) {
delete kv.second;
}
m_clients.clear();
}
}