110 lines
3.1 KiB
TypeScript
110 lines
3.1 KiB
TypeScript
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";
|
|
|
|
/**
|
|
* 应用启动状态
|
|
* 职责:
|
|
* - 初始化游戏引擎
|
|
* - 加载基础配置
|
|
* - 初始化网络管理器
|
|
* - 准备第一个UI界面
|
|
*/
|
|
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管理器...");
|
|
UIMgr.getInstance().setUIRoot(find("Canvas")!);
|
|
|
|
// 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] 初始化网络管理器...");
|
|
|
|
// 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() {
|
|
|
|
}
|
|
|
|
/**
|
|
* 退出启动状态
|
|
*/
|
|
onExit(): void {
|
|
super.onExit();
|
|
console.log("[AppStatusBoot] 离开启动状态");
|
|
}
|
|
}
|