重构NetManager支持MessagePair,新增TSRPCWsClient。

This commit is contained in:
janing
2025-12-18 13:25:04 +08:00
parent c12e439add
commit fb940452db
41 changed files with 976 additions and 681 deletions

View File

@@ -1,7 +1,10 @@
import { find } from "cc";
import { BaseState } from "../../Framework/FSM/BaseState";
import { NetConfig, NetProtocolType } from "../../Framework/Net/NetConfig";
import { NetEvent } from "../../Framework/Net/NetEvent";
import { NetManager } from "../../Framework/Net/NetManager";
import { UIMgr } from "../../Framework/UI/UIMgr";
import { serviceProto } from "../../Shared/protocols/serviceProto";
/**
* 应用启动状态
@@ -15,15 +18,15 @@ export class AppStatusBoot extends BaseState {
constructor(fsm: any) {
super(fsm, "Boot");
}
/**
* 进入启动状态
*/
async onEnter(params?: any): Promise<void> {
super.onEnter(params);
console.log("[AppStatusBoot] 开始初始化应用...");
try {
// 初始化UI
console.log("[AppStatusBoot] 初始化UI管理器...");
@@ -31,32 +34,71 @@ export class AppStatusBoot extends BaseState {
// 1. 初始化并连接网络
await this.initAndConnectNet();
// 2. 初始化完成,切换到登录状态
console.log("[AppStatusBoot] 启动完成,切换到登录状态");
this._fsm.changeState("Login");
} catch (error) {
console.error("[AppStatusBoot] 初始化失败:", error);
}
}
/**
* 初始化并连接网络
*/
private async initAndConnectNet(): Promise<void> {
console.log("[AppStatusBoot] 初始化网络管理器...");
// TODO: 从配置文件读取服务器地址
// import { serviceProto } from '../../Shared/protocols/serviceProto';
// const netManager = NetManager.getInstance();
// netManager.setServiceProto(serviceProto);
// netManager.init({ serverUrl: 'http://localhost:3000' });
// await netManager.connect();
console.log("[AppStatusBoot] 网络连接完成(待配置)");
// 1. 获取网络管理器实例
const netManager = NetManager.getInstance();
// 2. 设置服务协议 (必须在 init 之前调用)
netManager.setServiceProto(serviceProto);
// 3. 监听网络事件
netManager.on(NetEvent.Connected, () => {
console.log('✅ 网络已连接');
this.onConnected();
});
netManager.on(NetEvent.Disconnected, () => {
console.log('❌ 网络已断开');
});
netManager.on(NetEvent.Reconnecting, (count: number) => {
console.log(`🔄 正在重连... (${count})`);
});
netManager.on(NetEvent.Error, (error: any) => {
console.error('⚠️ 网络错误:', error);
});
const config: NetConfig = {
serverUrl: 'http://localhost:3000', // TODO: 替换为实际服务器地址
protocolType: NetProtocolType.WebSocket,
timeout: 30000,
autoReconnect: true,
reconnectInterval: 3000,
maxReconnectTimes: 5
};
// 5. 初始化
netManager.init(config);
// 6. 连接服务器 (HttpClient 创建即可用)
const success = await netManager.connect();
if (success) {
console.log('[AppStatusBoot]✅ 网络初始化成功');
} else {
console.error('[AppStatusBoot]❌ 网络初始化失败');
}
}
private onConnected() {
}
/**
* 退出启动状态
*/

View File

@@ -1,8 +1,9 @@
import { find } from "cc";
import { BaseState } from "../../Framework/FSM/BaseState";
import { UIMgr } from "../../Framework/UI/UIMgr";
import { PlayerInfo } from "../../Shared/protocols/MsgResLogin";
import { UIGame } from "../Game/UIGame";
import { World } from "../Game/World";
import { PlayerInfo } from "../../Shared/protocols/PtlLogin";
/**
* 应用游戏状态
@@ -16,19 +17,19 @@ export class AppStatusGame extends BaseState {
private _player: PlayerInfo = null;
private _isNewPlayer: boolean = false;
private _uiGame: UIGame = null;
constructor(fsm: any) {
super(fsm, "Game");
}
/**
* 进入游戏状态
*/
async onEnter(params?: any): Promise<void> {
super.onEnter(params);
console.log("[AppStatusGame] 进入游戏世界");
// 保存玩家信息
if (params) {
this._player = params.player || null;
@@ -36,82 +37,82 @@ export class AppStatusGame extends BaseState {
console.log(`[AppStatusGame] 玩家信息:`, this._player);
console.log(`[AppStatusGame] 是否新玩家: ${this._isNewPlayer}`);
}
try {
// 1. 加载游戏场景
await this.loadGameScene();
// 2. 初始化游戏
await this.initGame();
// 3. 开始监听服务器广播
this.listenServerMessages();
// 4. 开始游戏
this.startGame();
} catch (error) {
console.error("[AppStatusGame] 进入游戏失败:", error);
// 返回登录
this._fsm.changeState("Login");
}
}
/**
* 加载游戏场景
*/
private async loadGameScene(): Promise<void> {
console.log("[AppStatusGame] 加载游戏场景...");
// 加载游戏UI
this._uiGame = await UIMgr.getInstance().load(UIGame);
console.log("[AppStatusGame] 游戏场景加载完成");
}
/**
* 初始化游戏
*/
private async initGame(): Promise<void> {
console.log("[AppStatusGame] 初始化游戏...");
if (!this._uiGame) {
throw new Error("UIGame 未加载");
}
// 获取世界根节点
const worldRoot = this._uiGame.getWorldRoot();
const worldRoot = find("Game")
if (!worldRoot) {
throw new Error("世界根节点未找到");
}
// 初始化世界,传入本地玩家信息
await World.getInstance().init(worldRoot, this._player);
console.log("[AppStatusGame] 游戏初始化完成");
}
/**
* 监听服务器广播消息
*/
private listenServerMessages(): void {
console.log("[AppStatusGame] 开始监听服务器广播...");
// 网络消息监听已在 World 中注册
// World 会自动处理 MsgPlayerJoin 和 MsgPlayerMove
console.log("[AppStatusGame] 服务器广播监听已设置");
}
/**
* 开始游戏
*/
private startGame(): void {
console.log("[AppStatusGame] 游戏开始!");
// 游戏已启动,玩家可以通过 WASD 控制角色移动
}
/**
* 更新游戏状态(每帧调用)
*/
@@ -122,7 +123,7 @@ export class AppStatusGame extends BaseState {
// - 更新敌人AI
// - 同步网络状态
}
/**
* 暂停游戏
*/
@@ -132,7 +133,7 @@ export class AppStatusGame extends BaseState {
// - 停止游戏更新
// - 显示暂停菜单
}
/**
* 恢复游戏
*/
@@ -142,60 +143,60 @@ export class AppStatusGame extends BaseState {
// - 继续游戏更新
// - 隐藏暂停菜单
}
/**
* 玩家死亡
*/
onPlayerDeath(): void {
console.log("[AppStatusGame] 玩家死亡");
// TODO: 处理玩家死亡
// - 显示死亡界面
// - 显示复活选项或返回登录
// 延迟后返回登录
setTimeout(() => {
this._fsm.changeState("Login");
}, 3000);
}
/**
* 退出游戏(返回登录)
*/
quitGame(): void {
console.log("[AppStatusGame] 退出游戏");
// TODO: 断开连接或通知服务器
// const netManager = NetManager.getInstance();
// await netManager.disconnect();
// 返回登录
this._fsm.changeState("Login");
}
/**
* 延迟辅助函数
*/
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* 退出游戏状态
*/
onExit(): void {
super.onExit();
console.log("[AppStatusGame] 离开游戏状态");
// 清理世界
World.clear();
// 卸载游戏UI
if (this._uiGame) {
UIMgr.getInstance().unload(UIGame);
this._uiGame = null;
}
this._player = null;
}
}