This commit is contained in:
2025-10-26 20:44:58 +08:00
parent e287aadd3c
commit e73c08abf7
45 changed files with 280774 additions and 0 deletions

View File

@@ -0,0 +1,172 @@
#pragma once
#include "SocketWrapper.h"
#include <string>
#include <thread>
#include <atomic>
#include <memory>
#include <vector>
// 前向声明
class GameServer;
/**
* @brief 客户端状态枚举
*/
enum class ClientState {
Unauthenticated, // 未认证
Lobby, // 大厅中
InBattle // 战斗中
};
/**
* @brief 客户端处理器
*
* 技术点:
* 1. STL - std::thread (多线程)
* 2. 网络编程 - Socket 通信
*/
class ClientHandler : public std::enable_shared_from_this<ClientHandler> {
private:
int m_clientId;
SocketFd m_socketFd;
GameServer* m_server;
std::thread m_thread;
std::atomic<bool> m_isRunning;
// 客户端状态
ClientState m_state;
std::string m_username;
int m_userId;
// 战斗相关
std::string m_pendingInviter; // 待处理的邀请者
int m_battleRoomId; // 所在战斗房间ID
public:
/**
* @brief 构造函数
*/
ClientHandler(int clientId, SocketFd socketFd, GameServer* server);
/**
* @brief 析构函数
*/
~ClientHandler();
// 禁止拷贝
ClientHandler(const ClientHandler&) = delete;
ClientHandler& operator=(const ClientHandler&) = delete;
/**
* @brief 启动处理线程
*/
void start();
/**
* @brief 停止处理
*/
void stop();
/**
* @brief 发送消息
*/
bool sendMessage(const std::string& message);
/**
* @brief 获取客户端ID
*/
int getClientId() const { return m_clientId; }
/**
* @brief 获取用户名
*/
std::string getUsername() const { return m_username; }
/**
* @brief 获取用户ID
*/
int getUserId() const { return m_userId; }
/**
* @brief 获取状态
*/
ClientState getState() const { return m_state; }
/**
* @brief 设置状态
*/
void setState(ClientState state) { m_state = state; }
/**
* @brief 设置战斗房间ID
*/
void setBattleRoomId(int roomId) { m_battleRoomId = roomId; }
/**
* @brief 获取战斗房间ID
*/
int getBattleRoomId() const { return m_battleRoomId; }
/**
* @brief 设置待处理邀请
*/
void setPendingInviter(const std::string& inviter) { m_pendingInviter = inviter; }
/**
* @brief 获取待处理邀请
*/
std::string getPendingInviter() const { return m_pendingInviter; }
private:
/**
* @brief 线程主循环
*/
void run();
/**
* @brief 处理客户端命令
*/
void handleCommand(const std::string& command,
const std::vector<std::string>& params);
/**
* @brief 处理注册
*/
void handleRegister(const std::vector<std::string>& params);
/**
* @brief 处理登录
*/
void handleLogin(const std::vector<std::string>& params);
/**
* @brief 处理聊天
*/
void handleChat(const std::vector<std::string>& params);
/**
* @brief 处理玩家列表请求
*/
void handleListPlayers();
/**
* @brief 处理邀请
*/
void handleInvite(const std::vector<std::string>& params);
/**
* @brief 处理邀请响应
*/
void handleInviteResponse(const std::vector<std::string>& params);
/**
* @brief 处理战斗行动
*/
void handleBattleAction(const std::vector<std::string>& params);
/**
* @brief 处理登出
*/
void handleLogout();
};