SocketClient.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. const sproto = require('sproto');
  2. cc.Class({
  3. name: 'SocketClient',
  4. properties: {
  5. _clientHost: undefined,
  6. _clientSender: undefined,
  7. _ws: undefined,
  8. _session: 0,
  9. _reconnectTimes: 0,
  10. reconnectMaxTimes: 3,
  11. _connectTimeoutId: undefined,
  12. connectTimeout: 10000,
  13. host: undefined,
  14. _requestCmds: undefined,
  15. _requestModels: undefined,
  16. _responseHandlers: undefined,
  17. keepalive: 'h5user_keepalive'
  18. },
  19. ctor() {
  20. this._requestCmds = {};
  21. this._requestModels = {};
  22. this._responseHandlers = {};
  23. },
  24. /**
  25. * 加载协议文件
  26. *
  27. * @author Wetion
  28. * @date 2019-03-22
  29. * @param {Array} protoPaths
  30. */
  31. loadProtoFiles(protoPaths) {
  32. if (this._clientHost && this._clientSender) {
  33. G.LogUtils.warn('Warn:SocketClient协议文件已经加载过');
  34. return;
  35. }
  36. if (!G.FuncUtils.isArray(protoPaths)) {
  37. G.LogUtils.warn('Warn:SocketClient加载协议文件参数不正确');
  38. return;
  39. }
  40. // 加载协议文件
  41. cc.loader.loadResArray(protoPaths, (err, assets) => {
  42. if (err) {
  43. G.LogUtils.error('Bug:SocketClient协议文件失败 ' + err);
  44. return;
  45. }
  46. // 做个异步处理
  47. let protos = {};
  48. assets.forEach(proto => {
  49. let schema = JSON.parse(proto.text);
  50. let data = sproto.createNew(new Uint8Array(schema));
  51. protos[proto._name] = data;
  52. });
  53. this._clientHost = protos.socket_s2c.host();
  54. this._clientSender = this._clientHost.attach(protos.socket_c2s);
  55. G.LogUtils.log('Info:SocketClient协议文件加载成功');
  56. cc.game.emit('e_nwk_socket_sproto_done');
  57. // 释放资源
  58. for (const path of protoPaths) {
  59. cc.loader.releaseRes(path);
  60. }
  61. });
  62. },
  63. /**
  64. * 是否准备完成(发送消息的前提)
  65. *
  66. * @author Wetion
  67. * @date 2019-03-22
  68. * @returns {boolean}
  69. */
  70. isReadyDone() {
  71. return this._ws && this._ws.readyState === WebSocket.OPEN && this._clientHost && this._clientSender;
  72. },
  73. _isValidURLArgs(host, port) {
  74. return (G.FuncUtils.isIP(host) && G.FuncUtils.isPort(port) || G.FuncUtils.isDomain(host));
  75. },
  76. /**
  77. * 连接Socket
  78. *
  79. * @author Wetion
  80. * @date 2019-03-22
  81. * @param {String} host
  82. * @param {Number} port
  83. */
  84. connect(host, port) {
  85. if (!this._isValidURLArgs(host, port)) {
  86. G.LogUtils.error('Bug:SocketClient连接信息错误');
  87. return;
  88. }
  89. if (this._ws) {
  90. // 关闭旧连接
  91. this.close();
  92. }
  93. // 连接服务器
  94. this.host = host;
  95. this.port = port;
  96. let url = cc.js.formatStr('ws://%s:%s', host, port);
  97. if (G.FuncUtils.isIP(host)) {
  98. url = cc.js.formatStr('ws://%s:%s', host, port);
  99. } else {
  100. url = cc.js.formatStr('wss://%s', host);
  101. }
  102. url = cc.js.formatStr('ws://%s:%s', host, port);
  103. this._ws = new WebSocket(url, 'chat', cc.url.raw('resources/res_text/proto/cacert.pem'));
  104. this._ws.binaryType = 'arraybuffer';
  105. this._ws.onopen = this._onConnect.bind(this);
  106. this._ws.onmessage = this._onMessage.bind(this);
  107. this._ws.onerror = this._onError.bind(this);
  108. this._ws.onclose = this._onClose.bind(this);
  109. },
  110. _send(protoName, info, session) {
  111. let requestBuffer = G.FuncUtils.uint8ToBuffer(this._clientSender(protoName, info, session));
  112. this._ws.send(requestBuffer); // 发送数据
  113. },
  114. reconnect() {
  115. this.connect(this.host, this.port);
  116. },
  117. /**
  118. * 关闭Socket,不管处于什么状态
  119. */
  120. close() {
  121. if (!this._ws) {
  122. return;
  123. }
  124. this._ws.onopen = undefined;
  125. this._ws.onmessage = undefined;
  126. this._ws.onerror = undefined;
  127. this._ws.onclose = undefined;
  128. if (this._ws.readyState == WebSocket.CONNECTING || this._ws.readyState == WebSocket.OPEN) {
  129. this._ws.close();
  130. cc.game.emit('e_socket_on_closed', 'call_close');
  131. }
  132. this._ws = undefined;
  133. },
  134. /**
  135. * 客户端请求服务器信息
  136. *
  137. * @author Wetion
  138. * @date 2019-03-22
  139. * @param {String} protoName
  140. * @param {Object} info
  141. * @param {Function} responseHandler
  142. * @returns {Boolean} 是否成功发送
  143. */
  144. c2sRequest(protoName, info, responseHandler) {
  145. if (!this.isReadyDone()) {
  146. return;
  147. }
  148. this._session++;
  149. this._requestCmds[this._session] = protoName;
  150. this._requestModels[this._session] = info;
  151. this._responseHandlers[this._session] = responseHandler;
  152. if (protoName !== this.keepalive) {
  153. G.LogUtils.log('--> 网络请求 socket session:', this._session, 'proto name:', protoName, ' request info:', info);
  154. }
  155. this._send(protoName, info, this._session); // 发送数据
  156. return true;
  157. },
  158. c2sResponse(buffer) {
  159. let protoName = this._requestCmds[buffer.session];
  160. if (protoName !== this.keepalive) {
  161. G.LogUtils.log('<-- 网络返回 socket session:', buffer.session, 'proto name:', protoName, ' response info:', buffer.result);
  162. }
  163. let requestInfo = this._requestModels[buffer.session];
  164. let responseHandler = this._responseHandlers[buffer.session];
  165. if (responseHandler) {
  166. responseHandler({ requestInfo: requestInfo, responseInfo: buffer.result });
  167. }
  168. },
  169. s2cRequest(buffer) {
  170. G.LogUtils.log('<~~ 网络通知 socket pname:', buffer.pname, ' request info:', buffer.result);
  171. cc.game.emit(buffer.pname, buffer.result);
  172. },
  173. _onConnect(evt) {
  174. G.LogUtils.log('连接成功 ', evt);
  175. cc.game.emit('e_socket_on_connected');
  176. },
  177. _onMessage(evt) {
  178. // 解析数据
  179. let buffer = this._clientHost.dispatch(G.FuncUtils.bufferToUint8(evt.data));
  180. if (buffer.type === 'REQUEST') {
  181. // 避免native释放buffer导致 object already destroyed
  182. buffer.result = G.FuncUtils.clone(buffer.result);
  183. this.s2cRequest(buffer);
  184. } else if (buffer.type === 'RESPONSE') {
  185. // 避免native释放buffer导致 object already destroyed
  186. buffer.result = G.FuncUtils.clone(buffer.result);
  187. this.c2sResponse(buffer);
  188. } else {
  189. G.LogUtils.warn('不能解析的类型', buffer);
  190. }
  191. },
  192. _onError(err) {
  193. G.LogUtils.log('连接错误:', err);
  194. if (this._ws) {
  195. // 因为onerror后会马上触发onclose
  196. // 避免发两次 e_socket_on_closed 消息
  197. this._ws.onopen = undefined;
  198. this._ws.onmessage = undefined;
  199. this._ws.onerror = undefined;
  200. this._ws.onclose = undefined;
  201. this._ws = undefined;
  202. }
  203. cc.game.emit('e_socket_on_closed', 'on_error');
  204. },
  205. _onClose(evt) {
  206. G.LogUtils.log('连接关闭:', evt);
  207. if (this._ws) {
  208. // 收到关闭消息后对当前连接进行清理
  209. this._ws.onopen = undefined;
  210. this._ws.onmessage = undefined;
  211. this._ws.onerror = undefined;
  212. this._ws.onclose = undefined;
  213. this._ws = undefined;
  214. }
  215. cc.game.emit('e_socket_on_closed', 'on_close');
  216. }
  217. });