Ws.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. /**
  2. * Initialize a new `Emitter`.
  3. *
  4. * @api public
  5. */
  6. function Emitter(obj) {
  7. if (obj) return mixin(obj);
  8. };
  9. /**
  10. * Mixin the emitter properties.
  11. *
  12. * @param {Object} obj
  13. * @return {Object}
  14. * @api private
  15. */
  16. function mixin(obj) {
  17. for (var key in Emitter.prototype) {
  18. obj[key] = Emitter.prototype[key];
  19. }
  20. return obj;
  21. }
  22. /**
  23. * Listen on the given `event` with `fn`.
  24. *
  25. * @param {String} event
  26. * @param {Function} fn
  27. * @return {Emitter}
  28. * @api public
  29. */
  30. Emitter.prototype.on =
  31. Emitter.prototype.addEventListener = function (event, fn) {
  32. this._callbacks = this._callbacks || {};
  33. (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
  34. .push(fn);
  35. return this;
  36. };
  37. /**
  38. * Adds an `event` listener that will be invoked a single
  39. * time then automatically removed.
  40. *
  41. * @param {String} event
  42. * @param {Function} fn
  43. * @return {Emitter}
  44. * @api public
  45. */
  46. Emitter.prototype.once = function (event, fn) {
  47. function on() {
  48. this.off(event, on);
  49. fn.apply(this, arguments);
  50. }
  51. on.fn = fn;
  52. this.on(event, on);
  53. return this;
  54. };
  55. /**
  56. * Remove the given callback for `event` or all
  57. * registered callbacks.
  58. *
  59. * @param {String} event
  60. * @param {Function} fn
  61. * @return {Emitter}
  62. * @api public
  63. */
  64. Emitter.prototype.off =
  65. Emitter.prototype.removeListener =
  66. Emitter.prototype.removeAllListeners =
  67. Emitter.prototype.removeEventListener = function (event, fn) {
  68. this._callbacks = this._callbacks || {};
  69. // all
  70. if (0 == arguments.length) {
  71. this._callbacks = {};
  72. return this;
  73. }
  74. // specific event
  75. var callbacks = this._callbacks['$' + event];
  76. if (!callbacks) return this;
  77. // remove all handlers
  78. if (1 == arguments.length) {
  79. delete this._callbacks['$' + event];
  80. return this;
  81. }
  82. // remove specific handler
  83. var cb;
  84. for (var i = 0; i < callbacks.length; i++) {
  85. cb = callbacks[i];
  86. if (cb === fn || cb.fn === fn) {
  87. callbacks.splice(i, 1);
  88. break;
  89. }
  90. }
  91. return this;
  92. };
  93. /**
  94. * Emit `event` with the given args.
  95. *
  96. * @param {String} event
  97. * @param {Mixed} ...
  98. * @return {Emitter}
  99. */
  100. Emitter.prototype.emit = function (event) {
  101. this._callbacks = this._callbacks || {};
  102. var args = [].slice.call(arguments, 1),
  103. callbacks = this._callbacks['$' + event];
  104. if (callbacks) {
  105. callbacks = callbacks.slice(0);
  106. for (var i = 0, len = callbacks.length; i < len; ++i) {
  107. callbacks[i].apply(this, args);
  108. }
  109. }
  110. return this;
  111. };
  112. /**
  113. * Return array of callbacks for `event`.
  114. *
  115. * @param {String} event
  116. * @return {Array}
  117. * @api public
  118. */
  119. Emitter.prototype.listeners = function (event) {
  120. this._callbacks = this._callbacks || {};
  121. return this._callbacks['$' + event] || [];
  122. };
  123. /**
  124. * Check if this emitter has `event` handlers.
  125. *
  126. * @param {String} event
  127. * @return {Boolean}
  128. * @api public
  129. */
  130. Emitter.prototype.hasListeners = function (event) {
  131. return !!this.listeners(event).length;
  132. };
  133. function bind(obj, fn) {
  134. if ('string' == typeof fn) fn = obj[fn];
  135. if ('function' != typeof fn) throw new Error('bind() requires a function');
  136. var args = [].slice.call(arguments, 2);
  137. return function () {
  138. return fn.apply(obj, args.concat([].slice.call(arguments)));
  139. }
  140. };
  141. /**
  142. * WebSocket管理器
  143. * 支持最多同时实例化5个socket连接(微信环境限制目前最多为5个)
  144. * @param {String} url socket地址
  145. * @param {Object} opts 配置
  146. *
  147. */
  148. function WsManager(url, opts) {
  149. if(!(this instanceof WsManager)) {
  150. return new WsManager(url, opts)
  151. }
  152. if(url && (typeof url == 'object')) {
  153. opts = url
  154. url = undefined
  155. }
  156. Emitter(this)
  157. opts = opts || {}
  158. opts.path = opts.path || '/'
  159. this.opts = opts
  160. this.url = `${url}?uid=${GameGlobal.user.uid}&token=${GameGlobal.user.token}&channel=${GameGlobal.channel}&ver=${GameGlobal.os}&os=${GameGlobal.ver}`
  161. this.lastPing = null
  162. // this.socketCache = [] //缓存socket队列
  163. this.socketMaxCache = 5 //最大缓存socket实例数量
  164. this.readyState = 'closed' //当前socket状态
  165. this.binaryType = opts.binaryType || 'blob' //数据传输类型
  166. this._reconnectTimes = 0 //重连次数
  167. this._reconnectionDelay = opts.reconnectionDelay || 3000 //重连延迟
  168. this.reconnection(opts.reconnection !== false) // 是否自动重连
  169. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity) //重连最大尝试次数
  170. this.timeout(null == opts.timeout ? 20000 : opts.timeout)
  171. this.logStyle = 'color:blue; font-size:16px;font-weight:bold;'
  172. this.keepAliveInterval = 15000;
  173. this.keepAliveTimeout = null;
  174. this.keepAliveMsg = '0';
  175. this.autoConnect = opts.autoConnect !== false //是否自动连接
  176. if(this.autoConnect) {
  177. this.connect()
  178. }
  179. }
  180. WsManager.prototype.connect = function(fn) {
  181. if(~this.readyState.indexOf('open')) {
  182. return this
  183. }
  184. this.readyState = 'opening';
  185. if (window.tt != undefined) {
  186. this.socket = this.openTTConnect();
  187. } else if (CC_QQPLAY) {
  188. this.socket = this.openQQConnect();
  189. } else if (CC_WECHATGAME) {
  190. this.socket = this.openWxConnect();
  191. } else {
  192. this.socket = this.openH5Connect()
  193. }
  194. // this.socketCache.push(_socket)
  195. }
  196. WsManager.prototype.reconnect = function() {
  197. // clearInterval(this.keepAliveTimeout);
  198. if(this._reconnectTimes < this._reconnectionAttempts) {
  199. if(this.socket) {
  200. this.socket.close();
  201. }
  202. this._reconnectTimes += 1
  203. console.log(`%c [Socket正在尝试第${this._reconnectTimes}次重连]`, this.logStyle);
  204. this.readyState = 'reconnecting'
  205. setTimeout(() => {
  206. if (window.tt != undefined) {
  207. this.socket = this.openTTConnect();
  208. } else if (CC_QQPLAY) {
  209. this.socket = this.openQQConnect();
  210. } else if (CC_WECHATGAME) {
  211. this.socket = this.openWxConnect();
  212. } else {
  213. this.socket = this.openH5Connect()
  214. }
  215. }, this._reconnectionDelay);
  216. } else {
  217. if(this.socket) {
  218. this.socket.close();
  219. }
  220. console.log(`%c [达到最大重连失败次数,Socket关闭]`, this.logStyle);
  221. }
  222. }
  223. /// 外部调用直接关闭socket
  224. WsManager.prototype.close = function() {
  225. clearInterval(this.keepAliveTimeout);
  226. if(this.socket) {
  227. // let index = this.socketCache.indexOf(this.socket);
  228. // if (index != -1){
  229. // this.socketCache.splice(index, 1);
  230. // }
  231. this.socket.close();
  232. this._reconnection = false;
  233. }
  234. }
  235. WsManager.prototype.keepAlive = function() {
  236. let alivemsg = this.keepAliveMsg
  237. this.keepAliveTimeout = setInterval(() => {
  238. if(CC_WECHATGAME) {
  239. this.socket.send({
  240. data: alivemsg
  241. })
  242. } else if (CC_QQPLAY) {
  243. this.socket.send(alivemsg)
  244. } else {
  245. // this.socket.binaryType = 'blob'
  246. this.socket.send(alivemsg)
  247. }
  248. }, this.keepAliveInterval)
  249. }
  250. WsManager.prototype.openWxConnect = function() {
  251. let _header = {}
  252. let _socket = wx.connectSocket({
  253. url: this.url,
  254. header: _header,
  255. success: function(ret) {}
  256. })
  257. _socket.onOpen((res) => {
  258. this.readyState = 'open'
  259. this.emit('open', res)
  260. console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  261. // 每隔一段时间发一个心跳包保持连接状态
  262. this.keepAlive();
  263. })
  264. _socket.onClose((res) => {
  265. this.readyState = 'closed';
  266. clearInterval(this.keepAliveTimeout);
  267. //只要关闭就重连(暂时性处理)并且不是在后台 不进行重连
  268. if(this._reconnection && !GameGlobal.isOnHide ) {
  269. this.reconnect();
  270. }
  271. this.emit('close', res)
  272. console.log(`%c [Socket连接关闭: ${res}]`, this.logStyle)
  273. })
  274. _socket.onMessage((res) => {
  275. if(res.data != 1) {
  276. this.emit('message', res.data)
  277. }
  278. GameGlobal._socketCount += 1;
  279. if (GameGlobal._socketCount > 10000) {
  280. GameGlobal._socketCount = 2;
  281. }
  282. console.log(`%c [接收到Socket消息: ${JSON.stringify(res.data)}]`, this.logStyle);
  283. })
  284. _socket.onError((res) => {
  285. this.readyState = 'closed';
  286. clearInterval(this.keepAliveTimeout);
  287. if(this._reconnection && !GameGlobal.isOnHide) {
  288. this.reconnect();
  289. } else {
  290. _socket.close();
  291. }
  292. this.emit('error', res.errMsg);
  293. console.log(`%c [Socket错误: ${res.errMsg}]`, this.logStyle);
  294. })
  295. return _socket;
  296. }
  297. WsManager.prototype.openQQConnect = function() {
  298. let ws = new BK.WebSocket(this.url);
  299. let self = this;
  300. ws.onOpen = function(ws) {
  301. self.readyState = 'open';
  302. self.emit('open', '打开qqwebSocket');
  303. console.log(`%c [Socket连接成功: ${self.url.split("&token")[0]}]`, self.logStyle);
  304. // 每隔一段时间发一个心跳包保持连接状态
  305. self.keepAlive();
  306. }
  307. ws.onClose = function(ws) {
  308. self.readyState = 'closed';
  309. clearInterval(this.keepAliveTimeout);
  310. //只要关闭就重连(暂时性处理)并且不是在后台 不进行重连
  311. if(this._reconnection && !GameGlobal.isOnHide ) {
  312. this.reconnect();
  313. }
  314. self.emit('close', 'qq websocket关闭');
  315. console.log(`%c [Socket连接关闭]`, self.logStyle);
  316. }
  317. ws.onError = function(ws) {
  318. this.readyState = 'closed';
  319. clearInterval(this.keepAliveTimeout);
  320. if(this._reconnection && !GameGlobal.isOnHide) {
  321. this.reconnect();
  322. } else {
  323. ws.close();
  324. }
  325. self.emit('error', 'error')
  326. console.log(`%c [Socket错误]`, self.logStyle);
  327. }
  328. ws.onMessage = function(ws, res) {
  329. if(res.data != 1) {
  330. let str = res.data.readAsString();
  331. self.emit('message', str);
  332. }
  333. console.log(`%c [接收到Socket消息: ${JSON.stringify(res.data)}]`, self.logStyle);
  334. }
  335. ws.connect();
  336. return ws;
  337. }
  338. //// 头条socket
  339. WsManager.prototype.openTTConnect = function() {
  340. let socketTask = tt.connectSocket({
  341. "url": this.url,
  342. });
  343. let self = this;
  344. socketTask.onOpen(() => {
  345. self.readyState = 'open';
  346. self.emit('open', '打开TTwebSocket');
  347. console.log(`%c [Socket连接成功: ${self.url.split("&token")[0]}]`, self.logStyle);
  348. // 每隔一段时间发一个心跳包保持连接状态
  349. self.keepAlive();
  350. });
  351. socketTask.onClose(() => {
  352. self.readyState = 'closed';
  353. clearInterval(this.keepAliveTimeout);
  354. //只要关闭就重连(暂时性处理)并且不是在后台 不进行重连
  355. if(this._reconnection && !GameGlobal.isOnHide ) {
  356. this.reconnect();
  357. }
  358. self.emit('close', '头条 websocket关闭');
  359. console.log(`%c [Socket连接关闭]`, self.logStyle);
  360. });
  361. socketTask.onError(error => {
  362. this.readyState = 'closed';
  363. clearInterval(this.keepAliveTimeout);
  364. if(this._reconnection && !GameGlobal.isOnHide) {
  365. this.reconnect();
  366. } else {
  367. socketTask.close();
  368. }
  369. self.emit(error, 'error')
  370. console.log(`%c [Socket错误] ${error}`, self.logStyle);
  371. });
  372. socketTask.onMessage(message => {
  373. console.log('socket message:', message);
  374. let data = message.data;
  375. if(data != 1) {
  376. if (Object.prototype.toString.call(data) === '[object ArrayBuffer]') {
  377. data = Codec.read(data);
  378. }
  379. this.emit('message', data)
  380. }
  381. GameGlobal._socketCount += 1;
  382. if (GameGlobal._socketCount > 10000) {
  383. GameGlobal._socketCount = 2;
  384. }
  385. console.log(`%c [接收到Socket消息: ${JSON.stringify(message.data)}]`, this.logStyle);
  386. });
  387. return socketTask;
  388. }
  389. WsManager.prototype.openH5Connect = function() {
  390. let _socket = new WebSocket(this.url);
  391. _socket.binaryType = "arraybuffer";
  392. _socket.onopen = (event) => {
  393. this.readyState = 'open'
  394. this.emit('open', event)
  395. console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  396. // 每隔一段时间发一个心跳包保持连接状态
  397. this.keepAlive()
  398. }
  399. _socket.onclose = (event) => {
  400. this.readyState = 'closed';
  401. let code = event.code
  402. let reason = event.reason
  403. let wasClean = event.wasClean
  404. //只要关闭就重连(暂时性处理)
  405. if(this._reconnection) {
  406. this.reconnect()
  407. }
  408. this.emit('close', event)
  409. console.log(`%c [Socket连接关闭: ${reason}]`, this.logStyle)
  410. }
  411. _socket.onmessage = (event) => {
  412. if(event.data != 1) {
  413. this.emit('message', event.data)
  414. }
  415. console.log(`%c [接收到Socket消息: ${event.data}]`, this.logStyle);
  416. }
  417. _socket.onerror = (event) => {
  418. if(this._reconnection) {
  419. this.reconnect()
  420. } else {
  421. _socket.close()
  422. }
  423. this.emit(event)
  424. console.log(`%c [Socket错误: ${JSON.stringify(event)}]`, this.logStyle);
  425. }
  426. return _socket
  427. }
  428. WsManager.prototype.send = function(data) {
  429. console.log(`%c [发送Socket数据: ${data}]`, this.logStyle);
  430. if(CC_WECHATGAME) {
  431. let buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
  432. this.socket.send({
  433. data: buffer,
  434. success: function(res) {
  435. console.log('Success: ', JSON.stringify(res));
  436. },
  437. fail: function(res) {
  438. console.log('Fail: ', JSON.stringify(res));
  439. },
  440. complete: function(res) {
  441. console.log('Complete: ', JSON.stringify(res));
  442. }
  443. })
  444. } else {
  445. this.socket.binaryType = this.binaryType
  446. this.socket.send(data);
  447. }
  448. }
  449. // WsManager.prototype.onOpen = function(res) {
  450. // if(CC_WECHATGAME) {
  451. // this.socket.onOpen((res) => {
  452. // this.readyState = 'open'
  453. // callback && callback(res)
  454. // console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  455. // })
  456. // } else {
  457. // this.socket.onopen = () => {
  458. // this.readyState = 'open'
  459. // callback && callback()
  460. // console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  461. // }
  462. // }
  463. // }
  464. // WsManager.prototype.onClose = function(callback) {
  465. // if(CC_WECHATGAME) {
  466. // this.socket.onClose((res) => {
  467. // this.readyState = 'closed'
  468. // callback && callback(res)
  469. // console.log(`%c [Socket连接关闭: ${res}]`, this.logStyle)
  470. // })
  471. // } else {
  472. // this.socket.onclose = (event) => {
  473. // this.readyState = 'closed';
  474. // let code = event.code
  475. // let reason = event.reason
  476. // let wasClean = event.wasClean
  477. // callback && callback(event)
  478. // console.log(`%c [Socket连接关闭: ${reason}]`, this.logStyle)
  479. // }
  480. // }
  481. // }
  482. // WsManager.prototype.onMessage = function(callback) {
  483. // if(CC_WECHATGAME) {
  484. // this.socket.onMessage((res) => {
  485. // let data = res.data
  486. // callback && callback(data)
  487. // console.log(`%c [接收到Socket消息: ${JSON.stringify(data)}]`, this.logStyle);
  488. // })
  489. // } else {
  490. // this.socket.onmessage = (event) => {
  491. // let data = event.data
  492. // callback && callback(data)
  493. // console.log(`%c [接收到Socket消息: ${JSON.stringify(data)}]`, this.logStyle);
  494. // }
  495. // }
  496. // }
  497. // WsManager.prototype.onError = function(callback) {
  498. // if(CC_WECHATGAME) {
  499. // this.socket.onError((res) => {
  500. // callback && callback(res.errMsg)
  501. // console.log(`%c [Socket错误: ${res.errMsg}]`, this.logStyle);
  502. // })
  503. // } else {
  504. // this.socket.onerror = (event) => {
  505. // callback && callback(event.data)
  506. // console.log(`%c [Socket错误: ${event.data}]`, this.logStyle);
  507. // }
  508. // }
  509. // }
  510. /**
  511. * 配置socket连接超时时间
  512. * @param {Number} v 连接超时时间
  513. * @return {WsManager} WsManager对象实例
  514. * @api public
  515. */
  516. WsManager.prototype.timeout = function(v) {
  517. if(!arguments.length) {
  518. return this._timeout
  519. }
  520. this._timeout = v
  521. return this
  522. }
  523. /**
  524. * 自动重连配置
  525. * @param {Boolean} v 是否自动重连true / false
  526. * @return {WsManager} WsManager对象实例
  527. * @api public
  528. */
  529. WsManager.prototype.reconnection = function(v) {
  530. if(!arguments.length) {
  531. return this._reconnection
  532. }
  533. this._reconnection = !!v
  534. return this
  535. }
  536. /**
  537. * 配置最大重连次数
  538. * @param {Number} v 最大重连次数
  539. * @return {WsManager} WsManager对象实例
  540. * @api public
  541. */
  542. WsManager.prototype.reconnectionAttempts = function(v) {
  543. if (!arguments.length) {
  544. return this._reconnectionAttempts
  545. }
  546. this._reconnectionAttempts = v
  547. return this
  548. }
  549. module.exports = WsManager
  550. // var Ws = function() {
  551. // this.socket = new io(Api.SocketLocal, {
  552. // autoConnect: false, //自动连接
  553. // reconnection: true, //断开自动重连
  554. // reconnectionDelay: 2000, //自动重连时间,默认为2000毫秒
  555. // reconnectionAttempts: 10, //最大重连尝试次数,默认为Infinity
  556. // forceNew: true, //
  557. // })
  558. // this.socket.on("connect", () => {
  559. // console.log(`Socket connected: ${Api.SocketLocal}`);
  560. // })
  561. // }
  562. // Ws.prototype.open = function() {
  563. // this.socket.open()
  564. // }
  565. // /**
  566. // * 监听Websocket事件
  567. // * @param {String} eventName 监听事件名称
  568. // * @param {Function} callback 事件触发回调
  569. // */
  570. // Ws.prototype.on = function(eventName, callback) {
  571. // if(eventName) {
  572. // this.socket.on(eventName, data => {
  573. // console.log(`Socket On Event: ${eventName}`);
  574. // callback && callback(data)
  575. // })
  576. // }
  577. // }
  578. // /**
  579. // * 上报Websocket报文
  580. // * @param {String} eventName 上报事件名
  581. // * @param {Object} data 上报数据
  582. // */
  583. // Ws.prototype.emit = function(eventName, data) {
  584. // if(eventName) {
  585. // console.log(`Socket Do Emit: ${eventName}`, data);
  586. // this.socket.emit(eventName, data);
  587. // }
  588. // }
  589. // module.exports = new Ws();