08ecc5fa925fc3fd11ef12d15f82b21f0039b613.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. System.register(["__unresolved_0", "cc", "__unresolved_1", "__unresolved_2", "__unresolved_3"], function (_export, _context) {
  2. "use strict";
  3. 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;
  4. 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); } }
  5. 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); }); }; }
  6. /**自定义同步游戏变量(只能以r_或p_开头,按帧率同步,重新进入会收到最新的数据)
  7. * 只有第一个参数有效,可加上第一个参数跟第一个参数同类型,用于接收改变前的数据
  8. * t_开头为队伍事件
  9. * r_开头 主机游戏数据 主机权限
  10. * revt_ 开头房间事件
  11. * p_ 开头玩家数据 玩家权限和主机ai权限
  12. * online 玩家在线下线状态
  13. * 尽量拆分数据类型,不要设置过于复杂的数据类型*/
  14. /**网络状态*/
  15. function isArrayBuffer(it) {
  16. try {
  17. return it instanceof ArrayBuffer;
  18. } catch (_) {
  19. return false;
  20. }
  21. }
  22. function _reportPossibleCrUseOfNetRoom(extras) {
  23. _reporterNs.report("NetRoom", "./NetRoom", _context.meta, extras);
  24. }
  25. function _reportPossibleCrUseOfNetTeam(extras) {
  26. _reporterNs.report("NetTeam", "./NetTeam", _context.meta, extras);
  27. }
  28. function _reportPossibleCrUseOfWsClient(extras) {
  29. _reporterNs.report("WsClient", "./WsClient", _context.meta, extras);
  30. }
  31. _export("ch_net", void 0);
  32. return {
  33. setters: [function (_unresolved_) {
  34. _reporterNs = _unresolved_;
  35. }, function (_cc) {
  36. _cclegacy = _cc.cclegacy;
  37. }, function (_unresolved_2) {
  38. NetRoom = _unresolved_2.NetRoom;
  39. }, function (_unresolved_3) {
  40. NetTeam = _unresolved_3.NetTeam;
  41. }, function (_unresolved_4) {
  42. WsClient = _unresolved_4.WsClient;
  43. }],
  44. execute: function () {
  45. _crd = true;
  46. _cclegacy._RF.push({}, "3f10au8XnFG2b0ZjXy1nl0i", "net", undefined);
  47. HEARTBEAT_INTERVAL = 1000; //每秒发送一次 Ping
  48. HEARTBEAT_TIMEOUT = 30000; //30 秒的断线超时
  49. DIRTYDATACHECK_INTERVAL = 200; //每200毫秒同步一次自定义游戏变量
  50. EVTCHECK_INTERVAL = 66; //每66毫秒同步一次自定义游戏事件
  51. RECONNECT_COUNT = 10; //默认重连次数
  52. RECONNECT_INTERVAL = 2000; //默认重连间隔
  53. PING = 'ping';
  54. PONG = 'pong'; //
  55. S2C_LOGIN_SUCCESS = 's2c_login_success';
  56. S2C_TEAM_SUCCESS = 's2c_team_success';
  57. S2C_JOIN_TEAM_FAIL = 's2c_join_team_fail';
  58. S2C_TEAM_USER_JOIN = 's2c_team_user_join';
  59. S2C_TEAM_USER_EXIT = 's2c_team_user_exit';
  60. S2C_TEAM_CHANGE_HOST = 's2c_team_change_host';
  61. S2C_USER_RECONNECT = 's2c_user_reconnect';
  62. S2C_USER_DISCONNECT = 's2c_user_disconnect';
  63. S2C_MATCH = 's2c_match';
  64. S2C_MATCH_SUCCESS = 's2c_match_success';
  65. S2C_MATCH_CANCEL = 's2c_match_cancel';
  66. S2C_ROOM_GAMEDATA_CHANGE = 's2c_room_gameData_change';
  67. S2C_USER_GAMEDATA_CHANGE = 's2c_user_gameData_change';
  68. S2C_ROOM_CHANGE_HOST = 's2c_room_change_host';
  69. S2C_ROOM_CLOSED = 's2c_room_closed';
  70. S2C_TALK = 's2c_talk';
  71. S2C_FINISH = 's2c_finish';
  72. S2C_SETTLEMENT = 's2c_settlement';
  73. S2C_READY = 's2c_ready';
  74. S2C_NOT_READY = 's2c_not_ready'; //
  75. C2S_UPDATE_USER_GAMEDATA = 'c2s_update_user_gameData';
  76. C2S_UPDATE_ROOM_GAMEDATA = 'c2s_update_room_gameData';
  77. C2S_SET_TEAM = 'c2s_set_team';
  78. C2S_JOIN_TEAM = 'c2s_join_team';
  79. C2S_EXIT_TEAM = 'c2s_exit_team';
  80. C2S_CLOSE_ROOM = 'c2s_close_room';
  81. C2S_ROOM_EXIT = 'c2s_room_exit';
  82. C2S_MESSAGE = 'c2s_message';
  83. C2S_MESSAGE_TO_HOST = 'c2s_message_to_host';
  84. C2S_MESSAGE_TO_OTHER = 'c2s_message_without_self';
  85. C2S_TALK = 'c2s_talk';
  86. C2S_BACKED_RETURN = 'c2s_backed_return';
  87. C2S_BACKED = 'c2s_to_backed';
  88. C2S_FINISH = 'c2s_finish'; //
  89. Ver = '0.1.8';
  90. /**客户端*/
  91. _export("ch_net", ch_net = class ch_net {
  92. _new_resolve(id) {
  93. return new Promise(resolve => this._callbacks[id] = resolve);
  94. }
  95. get ownLevel() {
  96. return this._lv;
  97. }
  98. _do_resolve(id, data) {
  99. var resolveCallback = this._callbacks[id];
  100. if (!resolveCallback) return false;
  101. resolveCallback(data);
  102. delete this._callbacks[id];
  103. return true;
  104. }
  105. get dataInterval() {
  106. return this.gameDataInterval * 0.001;
  107. }
  108. get evtInterval() {
  109. return this.gameEvtInterval * 0.001;
  110. }
  111. get isActive() {
  112. return this._ws && this._ws.isActive;
  113. }
  114. /**队伍信息*/
  115. get team() {
  116. return this._team;
  117. }
  118. /**是否在队伍中*/
  119. get inTeam() {
  120. return this._team != null && this._team.own != null;
  121. }
  122. /**房间信息*/
  123. get room() {
  124. return this._room;
  125. }
  126. /**是否在房间中*/
  127. get inRoom() {
  128. return this._room != null && !this._room.cloosed;
  129. }
  130. /**
  131. * 创建一个客户端
  132. */
  133. constructor() {
  134. /**连接状态事件*/
  135. this.state = chsdk.get_new_event();
  136. this._ws = null;
  137. this._url = void 0;
  138. this._ca = void 0;
  139. this.reconnection = void 0;
  140. this.reconnectCount = void 0;
  141. this.reconnectInterval = void 0;
  142. this.timeoutInterval = void 0;
  143. this.gameDataInterval = void 0;
  144. this.gameEvtInterval = void 0;
  145. this.timeout = null;
  146. this.json = false;
  147. this.heartbeatInterval = null;
  148. // 心跳定时器
  149. this.dirtyDataCheckInterval = null;
  150. //变量同步定时器
  151. this.evtCheckInterval = null;
  152. //事件同步定时器
  153. this._currentReconnectCount = 0;
  154. this._pingTime = 0;
  155. this._ping = 0;
  156. //ping值
  157. this._callbacks = {};
  158. this._waitSends = [];
  159. this._lv = {
  160. LowerRank: 0,
  161. Rank: 0,
  162. Star: 0
  163. };
  164. this._team = void 0;
  165. this._room = void 0;
  166. this._waitSends = [];
  167. this._callbacks = {};
  168. }
  169. /**初始化
  170. * @param url - 连接的地址 'ws://localhost:3000'
  171. * @param options - 可选的配置选项对象,支持以下属性:
  172. * - **ca**: (可选) CA 证书字符串,用于 SSL 连接的验证。
  173. * - **reconnection**: (可选) 指示是否启用重连机制,默认为 `true`。
  174. * - **reconnectCount**: (可选) 在连接失败后重连的最大次数,默认值为 `10`。
  175. * - **reconnectInterval**: (可选) 每次重连之间的间隔时间,以毫秒为单位,默认值为 `2000` (2 秒)。
  176. * - **timeoutInterval**: (可选) 心跳断线时间,以毫秒为单位,默认值为 `30000` (30 秒)。
  177. * - **gameEvtInterval**:(可选) 游戏事件同步间隔,默认值为 `66` (0.06秒 1秒钟15次)。
  178. * - **gameDataInterval**:(可选) 游戏变量同步间隔,默认值为 `200` (0.2秒 1秒钟5次)。
  179. * - **json**: (可选) 是否用json序列化否则用messagepck 默认为 `false`。
  180. * @example
  181. * 自定义消息
  182. interface message extends message_protocol {
  183. useItem(userId: string, otherId: string, itemId: number): void//使用道具
  184. }
  185. 自定义数据
  186. export interface gd extends game_data {
  187. r_lv(lv: number);//关卡信息
  188. r_time(time: number);//关卡时间
  189. }
  190. export const net = ch.get_new_net<gd, message>();
  191. const url = chsdk.getUrl('/handle').replace(chsdk.getUrl('/handle').split(':')[0], 'ws');
  192. const token = chsdk.getToken();
  193. net.init(url,{query: `token=${token}`});
  194. */
  195. init(url, options) {
  196. var _options$query, _options$reconnection, _options$reconnectCou, _options$reconnectInt, _options$timeoutInter, _options$gameDataInte, _options$gameEvtInter, _options$json;
  197. this._url = url;
  198. this._url = "" + this._url + (options != null && (_options$query = options.query) != null && _options$query.length ? '?' + options.query : '');
  199. this._ca = options == null ? void 0 : options.ca;
  200. this.reconnection = (_options$reconnection = options == null ? void 0 : options.reconnection) != null ? _options$reconnection : true;
  201. this.reconnectCount = (_options$reconnectCou = options == null ? void 0 : options.reconnectCount) != null ? _options$reconnectCou : RECONNECT_COUNT;
  202. this.reconnectInterval = (_options$reconnectInt = options == null ? void 0 : options.reconnectInterval) != null ? _options$reconnectInt : RECONNECT_INTERVAL;
  203. this.timeoutInterval = (_options$timeoutInter = options == null ? void 0 : options.timeoutInterval) != null ? _options$timeoutInter : HEARTBEAT_TIMEOUT;
  204. this.gameDataInterval = (_options$gameDataInte = options == null ? void 0 : options.gameDataInterval) != null ? _options$gameDataInte : DIRTYDATACHECK_INTERVAL;
  205. this.gameEvtInterval = (_options$gameEvtInter = options == null ? void 0 : options.gameEvtInterval) != null ? _options$gameEvtInter : EVTCHECK_INTERVAL;
  206. this.json = (_options$json = options == null ? void 0 : options.json) != null ? _options$json : false;
  207. this._ws = new (_crd && WsClient === void 0 ? (_reportPossibleCrUseOfWsClient({
  208. error: Error()
  209. }), WsClient) : WsClient)(this._url, this._ca);
  210. this._ws.onConnected = this._onConnected.bind(this);
  211. this._ws.onError = this._onError.bind(this);
  212. this._ws.onClosing = this._onClosing.bind(this);
  213. this._ws.onClosed = this._onClosed.bind(this);
  214. this._ws.onMessage = this._onMessage.bind(this);
  215. var isbuffer = typeof ArrayBuffer !== 'undefined';
  216. console.log('ch_net 初始化 ver:', Ver, isbuffer, this.json, this._url); //
  217. chsdk.sdk_event.on('hide', this.on_hide, this);
  218. chsdk.sdk_event.on('show', this.on_show, this);
  219. }
  220. /**主动断开连接*/
  221. dispose() {
  222. this.state.clearAll();
  223. this._clear_team();
  224. this._clear_room();
  225. this._callbacks = {};
  226. this._waitSends.length = 0;
  227. this._ws.close(5000, 'client disconnect');
  228. chsdk.sdk_event.off('hide', this.on_hide, this);
  229. chsdk.sdk_event.off('show', this.on_show, this);
  230. }
  231. on_hide() {
  232. if (!this.inRoom) return;
  233. this.send_data(C2S_BACKED);
  234. }
  235. on_show() {
  236. if (!this.inRoom) return;
  237. this.send_data(C2S_BACKED_RETURN);
  238. }
  239. encode(msg) {
  240. return this.json ? JSON.stringify(msg) : msgpack.encode(msg);
  241. }
  242. decode(medata) {
  243. return isArrayBuffer(medata) ? msgpack.decode(new Uint8Array(medata)) : JSON.parse(medata);
  244. }
  245. send_data(type, data) {
  246. this._send(this.encode(data ? {
  247. type: type,
  248. data: data
  249. } : {
  250. type: type
  251. }));
  252. }
  253. /**开始连接,返回null为成功,否则为错误提示*/
  254. connect() {
  255. var _this = this;
  256. return _asyncToGenerator(function* () {
  257. if (!_this._ws) {
  258. chsdk.log.error('not init');
  259. return 'not init';
  260. }
  261. if (!_this._ws.connect()) return 'no netconnect';
  262. _this.state.emit(_this.state.key.Connecting);
  263. return _this._new_resolve('connect');
  264. })();
  265. }
  266. /**主动重新连接*/
  267. reconnect() {
  268. if (!this._ws) {
  269. chsdk.log.error('not init');
  270. return 'not init';
  271. }
  272. this._currentReconnectCount = 1;
  273. this.do_reconnect();
  274. }
  275. do_reconnect() {
  276. if (!this._ws.connect()) return;
  277. this.state.emit(this.state.key.Reconnecting, this._currentReconnectCount);
  278. }
  279. /**玩家创建队伍,返回null为成功,否则为错误提示*/
  280. creat_team(player_count) {
  281. var _this2 = this;
  282. return _asyncToGenerator(function* () {
  283. if (player_count === void 0) {
  284. player_count = 4;
  285. }
  286. if (!_this2._ws) return 'no netconnect';
  287. if (_this2.inTeam) return null;
  288. _this2.send_data(C2S_SET_TEAM, player_count);
  289. return _this2._new_resolve('creat_team');
  290. })();
  291. }
  292. /**玩家进入队伍,返回null为成功,否则为错误提示*/
  293. join_team(password) {
  294. var _this3 = this;
  295. return _asyncToGenerator(function* () {
  296. if (!_this3._ws) return 'no netconnect';
  297. if (_this3.inTeam) return null;
  298. _this3.send_data(C2S_JOIN_TEAM, {
  299. password: password
  300. });
  301. return _this3._new_resolve('join_team');
  302. })();
  303. }
  304. /**玩家退出队伍,返回null为成功,否则为错误提示*/
  305. exit_team() {
  306. var _this4 = this;
  307. return _asyncToGenerator(function* () {
  308. if (!_this4._ws) return 'no netconnect';
  309. if (!_this4.inTeam) return 'not in team';
  310. if (_this4.inRoom) return 'in game';
  311. _this4.send_data(C2S_EXIT_TEAM);
  312. return _this4._new_resolve('exit_team');
  313. })();
  314. }
  315. /**主机结束游戏关闭房间,成功后收到房间关闭事件*/
  316. close_room() {
  317. if (!this._ws) return;
  318. if (!this.inRoom) return;
  319. if (!this.room.isHost) return;
  320. this.send_data(C2S_CLOSE_ROOM);
  321. }
  322. /**玩家退出房间 ,返回null为成功,否则为错误提示,退出成功后收到房间关闭事件*/
  323. exit_room() {
  324. var _this5 = this;
  325. return _asyncToGenerator(function* () {
  326. if (!_this5._ws) return 'no netconnect';
  327. if (!_this5.inRoom) return 'not in room';
  328. _this5.send_data(C2S_ROOM_EXIT);
  329. return _this5._new_resolve('exit_room');
  330. })();
  331. }
  332. _clear_team() {
  333. var _this$_team;
  334. (_this$_team = this._team) == null || _this$_team.dispose();
  335. this._team = null;
  336. }
  337. _clear_room() {
  338. var _this$_room;
  339. if (!this._room) return;
  340. (_this$_room = this._room) == null || _this$_room.dispose();
  341. this._room = null;
  342. }
  343. _send(data) {
  344. if (!this._ws) return;
  345. if (this._ws.isActive) {
  346. this._ws.send(data);
  347. } else {
  348. this._waitSends.push(data);
  349. }
  350. }
  351. _updatePlayerStatus(id, online) {
  352. if (this.inTeam) this._team.updatePlayerStatus(id, online);
  353. if (this.inRoom) this._room.updatePlayerStatus(id, online);
  354. } //
  355. _onMessage(msg) {
  356. this.resetHeartbeat();
  357. try {
  358. var {
  359. data: medata
  360. } = msg;
  361. var _data = this.decode(medata);
  362. if (_data.type !== PONG) chsdk.log.log('receive', JSON.stringify(_data));
  363. switch (_data.type) {
  364. case PONG:
  365. this._ping = chsdk.date.now() - this._pingTime;
  366. chsdk.date.updateServerTime(_data.data); //chsdk.log.log("pong:", this._ping, data.data, chsdk.date.now());
  367. break;
  368. case S2C_LOGIN_SUCCESS:
  369. this._lv = _data.data;
  370. if (this._do_resolve('connect', null)) {
  371. this.state.emit(this.state.key.Connected);
  372. } else {
  373. this.state.emit(this.state.key.Reconnected);
  374. }
  375. this._callbacks = {};
  376. this.startHeartbeat();
  377. while (this._waitSends.length) {
  378. if (!this._ws) break;
  379. var _data2 = this._waitSends.shift();
  380. if (_data2) this._ws.send(_data2);
  381. }
  382. break;
  383. case S2C_TEAM_SUCCESS:
  384. if (this._team) this._clear_team();
  385. this._team = new (_crd && NetTeam === void 0 ? (_reportPossibleCrUseOfNetTeam({
  386. error: Error()
  387. }), NetTeam) : NetTeam)(_data.data, this.send_data.bind(this));
  388. if (!this._do_resolve('creat_team', null)) this._do_resolve('join_team', null);
  389. break;
  390. case S2C_JOIN_TEAM_FAIL:
  391. this._do_resolve('join_team', _data.data);
  392. break;
  393. case S2C_TEAM_USER_JOIN:
  394. var join_user = _data.data;
  395. join_user.status = true;
  396. this._team.addPlayer({
  397. key: join_user.userKey,
  398. data: join_user
  399. }, true);
  400. break;
  401. case S2C_TEAM_USER_EXIT:
  402. var esit_id = _data.data;
  403. if (esit_id === this._team.own.Id) {
  404. this._team.closed();
  405. this._clear_team();
  406. this._do_resolve('exit_team', null);
  407. } else {
  408. this._team.removePlayer(esit_id);
  409. }
  410. break;
  411. case S2C_TEAM_CHANGE_HOST:
  412. this._team.changeHost(_data.data);
  413. break;
  414. case S2C_ROOM_CHANGE_HOST:
  415. this._room.changeHost(_data.data);
  416. break;
  417. case S2C_USER_RECONNECT:
  418. this._updatePlayerStatus(_data.data, true);
  419. break;
  420. case S2C_USER_DISCONNECT:
  421. this._updatePlayerStatus(_data.data, false);
  422. break;
  423. case S2C_MATCH:
  424. this._team.match_start();
  425. break;
  426. case S2C_MATCH_CANCEL:
  427. this._team.match_cancel();
  428. break;
  429. case S2C_NOT_READY:
  430. this._team.not_ready();
  431. break;
  432. case S2C_READY:
  433. this._team.updatePlayerReady(_data.data, true);
  434. break;
  435. case S2C_MATCH_SUCCESS:
  436. this._clear_room();
  437. var roomData = _data.data.roomData;
  438. var pData = _data.data.playerData;
  439. this._room = new (_crd && NetRoom === void 0 ? (_reportPossibleCrUseOfNetRoom({
  440. error: Error()
  441. }), NetRoom) : NetRoom)(roomData, pData);
  442. if (this._team) this._team.match_success();
  443. break;
  444. case S2C_ROOM_GAMEDATA_CHANGE:
  445. this._room.server_change(_data.data);
  446. break;
  447. case S2C_USER_GAMEDATA_CHANGE:
  448. var p = this._room.getPlayer(_data.data.userKey);
  449. if (!p) break;
  450. p.server_change(_data.data.data);
  451. break;
  452. case S2C_ROOM_CLOSED:
  453. this._room.closed(_data.data);
  454. if (this.inTeam) {
  455. var list = this.room.all;
  456. for (var i = 0; i < list.length; i++) {
  457. var rp = list[i];
  458. if (rp.isAI) continue;
  459. var _p = this.team.getPlayer(rp.Id);
  460. if (!_p) continue;
  461. _p.set_level(rp.level, rp.rank, rp.score, rp.totalRank);
  462. }
  463. }
  464. this._do_resolve('exit_room', null);
  465. break;
  466. case S2C_TALK:
  467. if (this.inRoom) {
  468. this._room.onChat(_data.data.userKey, _data.data.msg);
  469. } else if (this.inTeam) {
  470. this._team.onChat(_data.data.userKey, _data.data.msg);
  471. }
  472. break;
  473. case S2C_FINISH:
  474. this._room.finish(_data.data.userKey, _data.data.rank);
  475. break;
  476. case S2C_SETTLEMENT:
  477. this._room.settlement(_data.data);
  478. break;
  479. case C2S_MESSAGE:
  480. if (Array.isArray(_data.data)) {
  481. for (var _i = 0; _i < _data.data.length; _i++) {
  482. var d = _data.data[_i];
  483. this._room._onEvt(d.type, d.data);
  484. }
  485. } else {
  486. chsdk.log.log('no def type:', _data.data); //(this.receive as any)._emit(data.type, data.data);
  487. }
  488. break;
  489. default:
  490. break;
  491. }
  492. } catch (error) {
  493. chsdk.log.warn(error);
  494. this.state.emit(this.state.key.Error, error);
  495. }
  496. }
  497. _onConnected(evt) {
  498. if (this.timeout) clearTimeout(this.timeout);
  499. this._currentReconnectCount = 0;
  500. this.timeout = setTimeout(() => {
  501. this._ws.close();
  502. chsdk.log.error("Closing connection.");
  503. }, 3000);
  504. }
  505. _onError(err) {
  506. chsdk.log.log('err', err);
  507. this.state.emit(this.state.key.Error, err);
  508. }
  509. _onClosing() {
  510. chsdk.log.log('closing');
  511. this.state.emit(this.state.key.Connecting);
  512. }
  513. _onClosed(event) {
  514. chsdk.log.log("WebSocket connection closed", event);
  515. this.stopHeartbeat();
  516. if (!this.reconnection || event.reason && event.code > 4000) {
  517. this.state.emit(this.state.key.Closed, event);
  518. this._do_resolve('connect', event);
  519. chsdk.log.log("WebSocket connection closed", event);
  520. return;
  521. }
  522. if (this._currentReconnectCount < this.reconnectCount) {
  523. this._currentReconnectCount += 1;
  524. chsdk.log.log("Reconnecting... Attempt " + this._currentReconnectCount);
  525. setTimeout(() => {
  526. this.do_reconnect();
  527. }, this.reconnectInterval);
  528. } else {
  529. chsdk.log.error("Max reconnect attempts reached. Giving up.");
  530. this.state.emit(this.state.key.Closed, event);
  531. this._do_resolve('connect', event);
  532. }
  533. }
  534. startHeartbeat() {
  535. this.heartbeatInterval = setInterval(() => {
  536. this.sendHeartbeat();
  537. }, HEARTBEAT_INTERVAL);
  538. this.dirtyDataCheckInterval = setInterval(() => {
  539. this.dirtyDataCheck();
  540. }, this.gameDataInterval);
  541. this.evtCheckInterval = setInterval(() => {
  542. this.evtCheck();
  543. }, this.gameEvtInterval);
  544. }
  545. resetHeartbeat() {
  546. if (this.timeout) clearTimeout(this.timeout);
  547. this.timeout = setTimeout(() => {
  548. chsdk.log.error("Heartbeat timeout. Closing connection.");
  549. this._ws.close();
  550. }, this.timeoutInterval);
  551. }
  552. sendHeartbeat() {
  553. this._pingTime = chsdk.date.now();
  554. this.send_data(PING, this._ping);
  555. }
  556. stopHeartbeat() {
  557. if (this.heartbeatInterval) clearInterval(this.heartbeatInterval);
  558. if (this.timeout) clearTimeout(this.timeout);
  559. if (this.dirtyDataCheckInterval) clearInterval(this.dirtyDataCheckInterval);
  560. if (this.evtCheckInterval) clearInterval(this.evtCheckInterval);
  561. }
  562. evtCheck() {
  563. var _this6 = this;
  564. if (this.inRoom) {
  565. this.room.doSendChat(msg => {
  566. if (!msg) return;
  567. this.send_data(C2S_TALK, msg);
  568. });
  569. this.room.doSendMode((mode0, mode1, mode2) => {
  570. if (mode0.length > 0) this.send_data(C2S_MESSAGE, mode0);
  571. if (mode1.length > 0) this.send_data(C2S_MESSAGE_TO_HOST, mode1);
  572. if (mode2.length > 0) this.send_data(C2S_MESSAGE_TO_OTHER, mode2);
  573. });
  574. var ps = this.room.all;
  575. var _loop = function _loop() {
  576. var p = ps[i];
  577. p.doFinishGame(() => {
  578. _this6.send_data(C2S_FINISH, p.Id);
  579. });
  580. };
  581. for (var i = 0; i < ps.length; i++) {
  582. _loop();
  583. }
  584. } else if (this.inTeam) {
  585. this.team.doSendChat(msg => {
  586. if (!msg) return;
  587. this.send_data(C2S_TALK, msg);
  588. });
  589. }
  590. }
  591. dirtyDataCheck() {
  592. var _this7 = this;
  593. if (!this.inRoom) return;
  594. this.room.own.doDirtyData(dirty => {
  595. this.send_data(C2S_UPDATE_USER_GAMEDATA, {
  596. userKey: this.room.own.Id,
  597. data: dirty
  598. });
  599. });
  600. if (!this.room.isHost) return;
  601. this._room.doDirtyData(dirty => {
  602. this.send_data(C2S_UPDATE_ROOM_GAMEDATA, dirty);
  603. });
  604. var ais = this.room.all;
  605. var _loop2 = function _loop2() {
  606. var ai = ais[i];
  607. ai.doDirtyData(dirty => {
  608. _this7.send_data(C2S_UPDATE_USER_GAMEDATA, {
  609. userKey: ai.Id,
  610. data: dirty
  611. });
  612. });
  613. };
  614. for (var i = 0; i < ais.length; i++) {
  615. _loop2();
  616. }
  617. }
  618. /**
  619. * 分享队伍信息,邀请进队
  620. * @param extend (可选)分享数据
  621. * @param title 分享显示标题
  622. * @param imageUrl 分享显示图片
  623. */
  624. shareNetTeam(title, imageUrl, extend) {
  625. if (!this.inTeam) return;
  626. chsdk.shareAppMessage(title, '', imageUrl, JSON.stringify({
  627. type: 'NetTeam',
  628. pw: this.team.Password,
  629. extends: extend
  630. }));
  631. }
  632. /**
  633. *获取从好友分享的net数据进入游戏的数据
  634. */
  635. getShareNetTeam() {
  636. var query = chsdk.getQuery();
  637. if (!query) return null;
  638. var message = query.message;
  639. if (!message) return null;
  640. var data = JSON.parse(message);
  641. if (!data) return null;
  642. if (data.type != 'NetTeam') return null;
  643. query.message = null;
  644. return {
  645. password: data.pw,
  646. extend: data.extends
  647. };
  648. }
  649. });
  650. _cclegacy._RF.pop();
  651. _crd = false;
  652. }
  653. };
  654. });
  655. //# sourceMappingURL=08ecc5fa925fc3fd11ef12d15f82b21f0039b613.js.map