System.register(["__unresolved_0", "cc", "__unresolved_1", "__unresolved_2", "__unresolved_3"], function (_export, _context) { "use strict"; var _reporterNs, _cclegacy, NetRoom, NetTeam, WsClient, ch_net, _crd, HEARTBEAT_INTERVAL, HEARTBEAT_TIMEOUT, DIRTYDATACHECK_INTERVAL, EVTCHECK_INTERVAL, RECONNECT_COUNT, RECONNECT_INTERVAL, PING, PONG, S2C_LOGIN_SUCCESS, S2C_TEAM_SUCCESS, S2C_JOIN_TEAM_FAIL, S2C_TEAM_USER_JOIN, S2C_TEAM_USER_EXIT, S2C_TEAM_CHANGE_HOST, S2C_USER_RECONNECT, S2C_USER_DISCONNECT, S2C_MATCH, S2C_MATCH_SUCCESS, S2C_MATCH_CANCEL, S2C_ROOM_GAMEDATA_CHANGE, S2C_USER_GAMEDATA_CHANGE, S2C_ROOM_CHANGE_HOST, S2C_ROOM_CLOSED, S2C_TALK, S2C_FINISH, S2C_SETTLEMENT, S2C_READY, S2C_NOT_READY, C2S_UPDATE_USER_GAMEDATA, C2S_UPDATE_ROOM_GAMEDATA, C2S_SET_TEAM, C2S_JOIN_TEAM, C2S_EXIT_TEAM, C2S_CLOSE_ROOM, C2S_ROOM_EXIT, C2S_MESSAGE, C2S_MESSAGE_TO_HOST, C2S_MESSAGE_TO_OTHER, C2S_TALK, C2S_BACKED_RETURN, C2S_BACKED, C2S_FINISH, Ver; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } /**自定义同步游戏变量(只能以r_或p_开头,按帧率同步,重新进入会收到最新的数据) * 只有第一个参数有效,可加上第一个参数跟第一个参数同类型,用于接收改变前的数据 * t_开头为队伍事件 * r_开头 主机游戏数据 主机权限 * revt_ 开头房间事件 * p_ 开头玩家数据 玩家权限和主机ai权限 * online 玩家在线下线状态 * 尽量拆分数据类型,不要设置过于复杂的数据类型*/ /**网络状态*/ function isArrayBuffer(it) { try { return it instanceof ArrayBuffer; } catch (_) { return false; } } function _reportPossibleCrUseOfNetRoom(extras) { _reporterNs.report("NetRoom", "./NetRoom", _context.meta, extras); } function _reportPossibleCrUseOfNetTeam(extras) { _reporterNs.report("NetTeam", "./NetTeam", _context.meta, extras); } function _reportPossibleCrUseOfWsClient(extras) { _reporterNs.report("WsClient", "./WsClient", _context.meta, extras); } _export("ch_net", void 0); return { setters: [function (_unresolved_) { _reporterNs = _unresolved_; }, function (_cc) { _cclegacy = _cc.cclegacy; }, function (_unresolved_2) { NetRoom = _unresolved_2.NetRoom; }, function (_unresolved_3) { NetTeam = _unresolved_3.NetTeam; }, function (_unresolved_4) { WsClient = _unresolved_4.WsClient; }], execute: function () { _crd = true; _cclegacy._RF.push({}, "3f10au8XnFG2b0ZjXy1nl0i", "net", undefined); HEARTBEAT_INTERVAL = 1000; //每秒发送一次 Ping HEARTBEAT_TIMEOUT = 30000; //30 秒的断线超时 DIRTYDATACHECK_INTERVAL = 200; //每200毫秒同步一次自定义游戏变量 EVTCHECK_INTERVAL = 66; //每66毫秒同步一次自定义游戏事件 RECONNECT_COUNT = 10; //默认重连次数 RECONNECT_INTERVAL = 2000; //默认重连间隔 PING = 'ping'; PONG = 'pong'; // S2C_LOGIN_SUCCESS = 's2c_login_success'; S2C_TEAM_SUCCESS = 's2c_team_success'; S2C_JOIN_TEAM_FAIL = 's2c_join_team_fail'; S2C_TEAM_USER_JOIN = 's2c_team_user_join'; S2C_TEAM_USER_EXIT = 's2c_team_user_exit'; S2C_TEAM_CHANGE_HOST = 's2c_team_change_host'; S2C_USER_RECONNECT = 's2c_user_reconnect'; S2C_USER_DISCONNECT = 's2c_user_disconnect'; S2C_MATCH = 's2c_match'; S2C_MATCH_SUCCESS = 's2c_match_success'; S2C_MATCH_CANCEL = 's2c_match_cancel'; S2C_ROOM_GAMEDATA_CHANGE = 's2c_room_gameData_change'; S2C_USER_GAMEDATA_CHANGE = 's2c_user_gameData_change'; S2C_ROOM_CHANGE_HOST = 's2c_room_change_host'; S2C_ROOM_CLOSED = 's2c_room_closed'; S2C_TALK = 's2c_talk'; S2C_FINISH = 's2c_finish'; S2C_SETTLEMENT = 's2c_settlement'; S2C_READY = 's2c_ready'; S2C_NOT_READY = 's2c_not_ready'; // C2S_UPDATE_USER_GAMEDATA = 'c2s_update_user_gameData'; C2S_UPDATE_ROOM_GAMEDATA = 'c2s_update_room_gameData'; C2S_SET_TEAM = 'c2s_set_team'; C2S_JOIN_TEAM = 'c2s_join_team'; C2S_EXIT_TEAM = 'c2s_exit_team'; C2S_CLOSE_ROOM = 'c2s_close_room'; C2S_ROOM_EXIT = 'c2s_room_exit'; C2S_MESSAGE = 'c2s_message'; C2S_MESSAGE_TO_HOST = 'c2s_message_to_host'; C2S_MESSAGE_TO_OTHER = 'c2s_message_without_self'; C2S_TALK = 'c2s_talk'; C2S_BACKED_RETURN = 'c2s_backed_return'; C2S_BACKED = 'c2s_to_backed'; C2S_FINISH = 'c2s_finish'; // Ver = '0.1.8'; /**客户端*/ _export("ch_net", ch_net = class ch_net { _new_resolve(id) { return new Promise(resolve => this._callbacks[id] = resolve); } get ownLevel() { return this._lv; } _do_resolve(id, data) { var resolveCallback = this._callbacks[id]; if (!resolveCallback) return false; resolveCallback(data); delete this._callbacks[id]; return true; } get dataInterval() { return this.gameDataInterval * 0.001; } get evtInterval() { return this.gameEvtInterval * 0.001; } get isActive() { return this._ws && this._ws.isActive; } /**队伍信息*/ get team() { return this._team; } /**是否在队伍中*/ get inTeam() { return this._team != null && this._team.own != null; } /**房间信息*/ get room() { return this._room; } /**是否在房间中*/ get inRoom() { return this._room != null && !this._room.cloosed; } /** * 创建一个客户端 */ constructor() { /**连接状态事件*/ this.state = chsdk.get_new_event(); this._ws = null; this._url = void 0; this._ca = void 0; this.reconnection = void 0; this.reconnectCount = void 0; this.reconnectInterval = void 0; this.timeoutInterval = void 0; this.gameDataInterval = void 0; this.gameEvtInterval = void 0; this.timeout = null; this.json = false; this.heartbeatInterval = null; // 心跳定时器 this.dirtyDataCheckInterval = null; //变量同步定时器 this.evtCheckInterval = null; //事件同步定时器 this._currentReconnectCount = 0; this._pingTime = 0; this._ping = 0; //ping值 this._callbacks = {}; this._waitSends = []; this._lv = { LowerRank: 0, Rank: 0, Star: 0 }; this._team = void 0; this._room = void 0; this._waitSends = []; this._callbacks = {}; } /**初始化 * @param url - 连接的地址 'ws://localhost:3000' * @param options - 可选的配置选项对象,支持以下属性: * - **ca**: (可选) CA 证书字符串,用于 SSL 连接的验证。 * - **reconnection**: (可选) 指示是否启用重连机制,默认为 `true`。 * - **reconnectCount**: (可选) 在连接失败后重连的最大次数,默认值为 `10`。 * - **reconnectInterval**: (可选) 每次重连之间的间隔时间,以毫秒为单位,默认值为 `2000` (2 秒)。 * - **timeoutInterval**: (可选) 心跳断线时间,以毫秒为单位,默认值为 `30000` (30 秒)。 * - **gameEvtInterval**:(可选) 游戏事件同步间隔,默认值为 `66` (0.06秒 1秒钟15次)。 * - **gameDataInterval**:(可选) 游戏变量同步间隔,默认值为 `200` (0.2秒 1秒钟5次)。 * - **json**: (可选) 是否用json序列化否则用messagepck 默认为 `false`。 * @example * 自定义消息 interface message extends message_protocol { useItem(userId: string, otherId: string, itemId: number): void//使用道具 } 自定义数据 export interface gd extends game_data { r_lv(lv: number);//关卡信息 r_time(time: number);//关卡时间 } export const net = ch.get_new_net(); const url = chsdk.getUrl('/handle').replace(chsdk.getUrl('/handle').split(':')[0], 'ws'); const token = chsdk.getToken(); net.init(url,{query: `token=${token}`}); */ init(url, options) { var _options$query, _options$reconnection, _options$reconnectCou, _options$reconnectInt, _options$timeoutInter, _options$gameDataInte, _options$gameEvtInter, _options$json; this._url = url; this._url = "" + this._url + (options != null && (_options$query = options.query) != null && _options$query.length ? '?' + options.query : ''); this._ca = options == null ? void 0 : options.ca; this.reconnection = (_options$reconnection = options == null ? void 0 : options.reconnection) != null ? _options$reconnection : true; this.reconnectCount = (_options$reconnectCou = options == null ? void 0 : options.reconnectCount) != null ? _options$reconnectCou : RECONNECT_COUNT; this.reconnectInterval = (_options$reconnectInt = options == null ? void 0 : options.reconnectInterval) != null ? _options$reconnectInt : RECONNECT_INTERVAL; this.timeoutInterval = (_options$timeoutInter = options == null ? void 0 : options.timeoutInterval) != null ? _options$timeoutInter : HEARTBEAT_TIMEOUT; this.gameDataInterval = (_options$gameDataInte = options == null ? void 0 : options.gameDataInterval) != null ? _options$gameDataInte : DIRTYDATACHECK_INTERVAL; this.gameEvtInterval = (_options$gameEvtInter = options == null ? void 0 : options.gameEvtInterval) != null ? _options$gameEvtInter : EVTCHECK_INTERVAL; this.json = (_options$json = options == null ? void 0 : options.json) != null ? _options$json : false; this._ws = new (_crd && WsClient === void 0 ? (_reportPossibleCrUseOfWsClient({ error: Error() }), WsClient) : WsClient)(this._url, this._ca); this._ws.onConnected = this._onConnected.bind(this); this._ws.onError = this._onError.bind(this); this._ws.onClosing = this._onClosing.bind(this); this._ws.onClosed = this._onClosed.bind(this); this._ws.onMessage = this._onMessage.bind(this); var isbuffer = typeof ArrayBuffer !== 'undefined'; console.log('ch_net 初始化 ver:', Ver, isbuffer, this.json, this._url); // chsdk.sdk_event.on('hide', this.on_hide, this); chsdk.sdk_event.on('show', this.on_show, this); } /**主动断开连接*/ dispose() { this.state.clearAll(); this._clear_team(); this._clear_room(); this._callbacks = {}; this._waitSends.length = 0; this._ws.close(5000, 'client disconnect'); chsdk.sdk_event.off('hide', this.on_hide, this); chsdk.sdk_event.off('show', this.on_show, this); } on_hide() { if (!this.inRoom) return; this.send_data(C2S_BACKED); } on_show() { if (!this.inRoom) return; this.send_data(C2S_BACKED_RETURN); } encode(msg) { return this.json ? JSON.stringify(msg) : msgpack.encode(msg); } decode(medata) { return isArrayBuffer(medata) ? msgpack.decode(new Uint8Array(medata)) : JSON.parse(medata); } send_data(type, data) { this._send(this.encode(data ? { type: type, data: data } : { type: type })); } /**开始连接,返回null为成功,否则为错误提示*/ connect() { var _this = this; return _asyncToGenerator(function* () { if (!_this._ws) { chsdk.log.error('not init'); return 'not init'; } if (!_this._ws.connect()) return 'no netconnect'; _this.state.emit(_this.state.key.Connecting); return _this._new_resolve('connect'); })(); } /**主动重新连接*/ reconnect() { if (!this._ws) { chsdk.log.error('not init'); return 'not init'; } this._currentReconnectCount = 1; this.do_reconnect(); } do_reconnect() { if (!this._ws.connect()) return; this.state.emit(this.state.key.Reconnecting, this._currentReconnectCount); } /**玩家创建队伍,返回null为成功,否则为错误提示*/ creat_team(player_count) { var _this2 = this; return _asyncToGenerator(function* () { if (player_count === void 0) { player_count = 4; } if (!_this2._ws) return 'no netconnect'; if (_this2.inTeam) return null; _this2.send_data(C2S_SET_TEAM, player_count); return _this2._new_resolve('creat_team'); })(); } /**玩家进入队伍,返回null为成功,否则为错误提示*/ join_team(password) { var _this3 = this; return _asyncToGenerator(function* () { if (!_this3._ws) return 'no netconnect'; if (_this3.inTeam) return null; _this3.send_data(C2S_JOIN_TEAM, { password: password }); return _this3._new_resolve('join_team'); })(); } /**玩家退出队伍,返回null为成功,否则为错误提示*/ exit_team() { var _this4 = this; return _asyncToGenerator(function* () { if (!_this4._ws) return 'no netconnect'; if (!_this4.inTeam) return 'not in team'; if (_this4.inRoom) return 'in game'; _this4.send_data(C2S_EXIT_TEAM); return _this4._new_resolve('exit_team'); })(); } /**主机结束游戏关闭房间,成功后收到房间关闭事件*/ close_room() { if (!this._ws) return; if (!this.inRoom) return; if (!this.room.isHost) return; this.send_data(C2S_CLOSE_ROOM); } /**玩家退出房间 ,返回null为成功,否则为错误提示,退出成功后收到房间关闭事件*/ exit_room() { var _this5 = this; return _asyncToGenerator(function* () { if (!_this5._ws) return 'no netconnect'; if (!_this5.inRoom) return 'not in room'; _this5.send_data(C2S_ROOM_EXIT); return _this5._new_resolve('exit_room'); })(); } _clear_team() { var _this$_team; (_this$_team = this._team) == null || _this$_team.dispose(); this._team = null; } _clear_room() { var _this$_room; if (!this._room) return; (_this$_room = this._room) == null || _this$_room.dispose(); this._room = null; } _send(data) { if (!this._ws) return; if (this._ws.isActive) { this._ws.send(data); } else { this._waitSends.push(data); } } _updatePlayerStatus(id, online) { if (this.inTeam) this._team.updatePlayerStatus(id, online); if (this.inRoom) this._room.updatePlayerStatus(id, online); } // _onMessage(msg) { this.resetHeartbeat(); try { var { data: medata } = msg; var _data = this.decode(medata); if (_data.type !== PONG) chsdk.log.log('receive', JSON.stringify(_data)); switch (_data.type) { case PONG: this._ping = chsdk.date.now() - this._pingTime; chsdk.date.updateServerTime(_data.data); //chsdk.log.log("pong:", this._ping, data.data, chsdk.date.now()); break; case S2C_LOGIN_SUCCESS: this._lv = _data.data; if (this._do_resolve('connect', null)) { this.state.emit(this.state.key.Connected); } else { this.state.emit(this.state.key.Reconnected); } this._callbacks = {}; this.startHeartbeat(); while (this._waitSends.length) { if (!this._ws) break; var _data2 = this._waitSends.shift(); if (_data2) this._ws.send(_data2); } break; case S2C_TEAM_SUCCESS: if (this._team) this._clear_team(); this._team = new (_crd && NetTeam === void 0 ? (_reportPossibleCrUseOfNetTeam({ error: Error() }), NetTeam) : NetTeam)(_data.data, this.send_data.bind(this)); if (!this._do_resolve('creat_team', null)) this._do_resolve('join_team', null); break; case S2C_JOIN_TEAM_FAIL: this._do_resolve('join_team', _data.data); break; case S2C_TEAM_USER_JOIN: var join_user = _data.data; join_user.status = true; this._team.addPlayer({ key: join_user.userKey, data: join_user }, true); break; case S2C_TEAM_USER_EXIT: var esit_id = _data.data; if (esit_id === this._team.own.Id) { this._team.closed(); this._clear_team(); this._do_resolve('exit_team', null); } else { this._team.removePlayer(esit_id); } break; case S2C_TEAM_CHANGE_HOST: this._team.changeHost(_data.data); break; case S2C_ROOM_CHANGE_HOST: this._room.changeHost(_data.data); break; case S2C_USER_RECONNECT: this._updatePlayerStatus(_data.data, true); break; case S2C_USER_DISCONNECT: this._updatePlayerStatus(_data.data, false); break; case S2C_MATCH: this._team.match_start(); break; case S2C_MATCH_CANCEL: this._team.match_cancel(); break; case S2C_NOT_READY: this._team.not_ready(); break; case S2C_READY: this._team.updatePlayerReady(_data.data, true); break; case S2C_MATCH_SUCCESS: this._clear_room(); var roomData = _data.data.roomData; var pData = _data.data.playerData; this._room = new (_crd && NetRoom === void 0 ? (_reportPossibleCrUseOfNetRoom({ error: Error() }), NetRoom) : NetRoom)(roomData, pData); if (this._team) this._team.match_success(); break; case S2C_ROOM_GAMEDATA_CHANGE: this._room.server_change(_data.data); break; case S2C_USER_GAMEDATA_CHANGE: var p = this._room.getPlayer(_data.data.userKey); if (!p) break; p.server_change(_data.data.data); break; case S2C_ROOM_CLOSED: this._room.closed(_data.data); if (this.inTeam) { var list = this.room.all; for (var i = 0; i < list.length; i++) { var rp = list[i]; if (rp.isAI) continue; var _p = this.team.getPlayer(rp.Id); if (!_p) continue; _p.set_level(rp.level, rp.rank, rp.score, rp.totalRank); } } this._do_resolve('exit_room', null); break; case S2C_TALK: if (this.inRoom) { this._room.onChat(_data.data.userKey, _data.data.msg); } else if (this.inTeam) { this._team.onChat(_data.data.userKey, _data.data.msg); } break; case S2C_FINISH: this._room.finish(_data.data.userKey, _data.data.rank); break; case S2C_SETTLEMENT: this._room.settlement(_data.data); break; case C2S_MESSAGE: if (Array.isArray(_data.data)) { for (var _i = 0; _i < _data.data.length; _i++) { var d = _data.data[_i]; this._room._onEvt(d.type, d.data); } } else { chsdk.log.log('no def type:', _data.data); //(this.receive as any)._emit(data.type, data.data); } break; default: break; } } catch (error) { chsdk.log.warn(error); this.state.emit(this.state.key.Error, error); } } _onConnected(evt) { if (this.timeout) clearTimeout(this.timeout); this._currentReconnectCount = 0; this.timeout = setTimeout(() => { this._ws.close(); chsdk.log.error("Closing connection."); }, 3000); } _onError(err) { chsdk.log.log('err', err); this.state.emit(this.state.key.Error, err); } _onClosing() { chsdk.log.log('closing'); this.state.emit(this.state.key.Connecting); } _onClosed(event) { chsdk.log.log("WebSocket connection closed", event); this.stopHeartbeat(); if (!this.reconnection || event.reason && event.code > 4000) { this.state.emit(this.state.key.Closed, event); this._do_resolve('connect', event); chsdk.log.log("WebSocket connection closed", event); return; } if (this._currentReconnectCount < this.reconnectCount) { this._currentReconnectCount += 1; chsdk.log.log("Reconnecting... Attempt " + this._currentReconnectCount); setTimeout(() => { this.do_reconnect(); }, this.reconnectInterval); } else { chsdk.log.error("Max reconnect attempts reached. Giving up."); this.state.emit(this.state.key.Closed, event); this._do_resolve('connect', event); } } startHeartbeat() { this.heartbeatInterval = setInterval(() => { this.sendHeartbeat(); }, HEARTBEAT_INTERVAL); this.dirtyDataCheckInterval = setInterval(() => { this.dirtyDataCheck(); }, this.gameDataInterval); this.evtCheckInterval = setInterval(() => { this.evtCheck(); }, this.gameEvtInterval); } resetHeartbeat() { if (this.timeout) clearTimeout(this.timeout); this.timeout = setTimeout(() => { chsdk.log.error("Heartbeat timeout. Closing connection."); this._ws.close(); }, this.timeoutInterval); } sendHeartbeat() { this._pingTime = chsdk.date.now(); this.send_data(PING, this._ping); } stopHeartbeat() { if (this.heartbeatInterval) clearInterval(this.heartbeatInterval); if (this.timeout) clearTimeout(this.timeout); if (this.dirtyDataCheckInterval) clearInterval(this.dirtyDataCheckInterval); if (this.evtCheckInterval) clearInterval(this.evtCheckInterval); } evtCheck() { var _this6 = this; if (this.inRoom) { this.room.doSendChat(msg => { if (!msg) return; this.send_data(C2S_TALK, msg); }); this.room.doSendMode((mode0, mode1, mode2) => { if (mode0.length > 0) this.send_data(C2S_MESSAGE, mode0); if (mode1.length > 0) this.send_data(C2S_MESSAGE_TO_HOST, mode1); if (mode2.length > 0) this.send_data(C2S_MESSAGE_TO_OTHER, mode2); }); var ps = this.room.all; var _loop = function _loop() { var p = ps[i]; p.doFinishGame(() => { _this6.send_data(C2S_FINISH, p.Id); }); }; for (var i = 0; i < ps.length; i++) { _loop(); } } else if (this.inTeam) { this.team.doSendChat(msg => { if (!msg) return; this.send_data(C2S_TALK, msg); }); } } dirtyDataCheck() { var _this7 = this; if (!this.inRoom) return; this.room.own.doDirtyData(dirty => { this.send_data(C2S_UPDATE_USER_GAMEDATA, { userKey: this.room.own.Id, data: dirty }); }); if (!this.room.isHost) return; this._room.doDirtyData(dirty => { this.send_data(C2S_UPDATE_ROOM_GAMEDATA, dirty); }); var ais = this.room.all; var _loop2 = function _loop2() { var ai = ais[i]; ai.doDirtyData(dirty => { _this7.send_data(C2S_UPDATE_USER_GAMEDATA, { userKey: ai.Id, data: dirty }); }); }; for (var i = 0; i < ais.length; i++) { _loop2(); } } /** * 分享队伍信息,邀请进队 * @param extend (可选)分享数据 * @param title 分享显示标题 * @param imageUrl 分享显示图片 */ shareNetTeam(title, imageUrl, extend) { if (!this.inTeam) return; chsdk.shareAppMessage(title, '', imageUrl, JSON.stringify({ type: 'NetTeam', pw: this.team.Password, extends: extend })); } /** *获取从好友分享的net数据进入游戏的数据 */ getShareNetTeam() { var query = chsdk.getQuery(); if (!query) return null; var message = query.message; if (!message) return null; var data = JSON.parse(message); if (!data) return null; if (data.type != 'NetTeam') return null; query.message = null; return { password: data.pw, extend: data.extends }; } }); _cclegacy._RF.pop(); _crd = false; } }; }); //# sourceMappingURL=258ef086e9da490ac24335c87b1f800202f98b70.js.map