mirror of
https://github.com/ChuXunYu/OnlineRpg.git
synced 2026-01-31 11:55:46 +00:00
112 lines
2.3 KiB
C++
112 lines
2.3 KiB
C++
#pragma once
|
|
#include "SocketWrapper.h"
|
|
#include "Database.h"
|
|
#include <string>
|
|
#include <map>
|
|
#include <mutex>
|
|
#include <memory>
|
|
#include <vector>
|
|
|
|
// 前向声明
|
|
class ClientHandler;
|
|
class GameLobby;
|
|
class BattleRoomManager;
|
|
|
|
/**
|
|
* @brief 游戏服务器主类
|
|
*
|
|
* 技术点:
|
|
* 1. STL - std::map, std::mutex, std::thread
|
|
* 2. 网络编程 - Socket Server
|
|
*/
|
|
class GameServer {
|
|
private:
|
|
int m_port;
|
|
SocketWrapper m_serverSocket;
|
|
std::shared_ptr<Database> m_database;
|
|
|
|
// 客户端管理 (STL)
|
|
std::map<int, std::shared_ptr<ClientHandler>> m_clients;
|
|
std::mutex m_clientsMutex;
|
|
int m_nextClientId;
|
|
|
|
// 游戏模块
|
|
std::shared_ptr<GameLobby> m_lobby;
|
|
std::shared_ptr<BattleRoomManager> m_battleManager;
|
|
|
|
bool m_isRunning;
|
|
|
|
public:
|
|
/**
|
|
* @brief 构造函数
|
|
* @param port 监听端口
|
|
* @param dbPath 数据库文件路径
|
|
*/
|
|
GameServer(int port, const std::string& dbPath);
|
|
|
|
/**
|
|
* @brief 析构函数
|
|
*/
|
|
~GameServer();
|
|
|
|
/**
|
|
* @brief 启动服务器
|
|
*/
|
|
bool start();
|
|
|
|
/**
|
|
* @brief 停止服务器
|
|
*/
|
|
void stop();
|
|
|
|
/**
|
|
* @brief 服务器主循环 (接受连接)
|
|
*/
|
|
void run();
|
|
|
|
/**
|
|
* @brief 添加客户端
|
|
*/
|
|
int addClient(std::shared_ptr<ClientHandler> client);
|
|
|
|
/**
|
|
* @brief 移除客户端
|
|
*/
|
|
void removeClient(int clientId);
|
|
|
|
/**
|
|
* @brief 根据用户名获取客户端
|
|
*/
|
|
std::shared_ptr<ClientHandler> getClientByUsername(const std::string& username);
|
|
|
|
/**
|
|
* @brief 获取所有在线玩家列表
|
|
*/
|
|
std::vector<std::string> getOnlinePlayers();
|
|
|
|
/**
|
|
* @brief 广播消息给所有在大厅的客户端
|
|
*/
|
|
void broadcastToLobby(const std::string& message, int excludeClientId = -1);
|
|
|
|
/**
|
|
* @brief 获取数据库
|
|
*/
|
|
std::shared_ptr<Database> getDatabase() { return m_database; }
|
|
|
|
/**
|
|
* @brief 获取大厅
|
|
*/
|
|
std::shared_ptr<GameLobby> getLobby() { return m_lobby; }
|
|
|
|
/**
|
|
* @brief 获取战斗管理器
|
|
*/
|
|
std::shared_ptr<BattleRoomManager> getBattleManager() { return m_battleManager; }
|
|
|
|
/**
|
|
* @brief 检查服务器是否运行中
|
|
*/
|
|
bool isRunning() const { return m_isRunning; }
|
|
};
|