Ws.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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=${Global.user.uid}&token=${Global.user.token}&channel=${Global.channel}&ver=${Global.os}&os=${Global.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 || 1000 //重连延迟
  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. let _socket = CC_WECHATGAME ? this.openWxConnect() : this.openH5Connect()
  186. // this.socketCache.push(_socket)
  187. this.socket = _socket;
  188. }
  189. WsManager.prototype.reconnect = function() {
  190. clearInterval(this.keepAliveTimeout);
  191. if(this._reconnectTimes < this._reconnectionAttempts) {
  192. if(this.socket) {
  193. this.socket.close();
  194. }
  195. this._reconnectTimes += 1
  196. console.log(`%c [Socket正在尝试第${this._reconnectTimes}次重连]`, this.logStyle);
  197. this.readyState = 'reconnecting'
  198. setTimeout(() => {
  199. this.socket = CC_WECHATGAME ? this.openWxConnect() : this.openH5Connect();
  200. }, this._reconnectionDelay);
  201. } else {
  202. if(this.socket) {
  203. this.socket.close();
  204. }
  205. console.log(`%c [达到最大重连失败次数,Socket关闭]`, this.logStyle);
  206. }
  207. }
  208. /// 外部调用直接关闭socket
  209. WsManager.prototype.close = function() {
  210. clearInterval(this.keepAliveTimeout);
  211. if(this.socket) {
  212. // let index = this.socketCache.indexOf(this.socket);
  213. // if (index != -1){
  214. // this.socketCache.splice(index, 1);
  215. // }
  216. this.socket.close();
  217. this._reconnection = false;
  218. }
  219. }
  220. WsManager.prototype.keepAlive = function() {
  221. let alivemsg = this.keepAliveMsg
  222. this.keepAliveTimeout = setInterval(() => {
  223. if(CC_WECHATGAME) {
  224. this.socket.send({
  225. data: alivemsg
  226. })
  227. } else {
  228. // this.socket.binaryType = 'blob'
  229. this.socket.send(alivemsg)
  230. }
  231. }, this.keepAliveInterval)
  232. }
  233. WsManager.prototype.openWxConnect = function() {
  234. let _header = {}
  235. let _socket = wx.connectSocket({
  236. url: this.url,
  237. header: _header,
  238. success: function(ret) {}
  239. })
  240. _socket.onOpen((res) => {
  241. this.readyState = 'open'
  242. this.emit('open', res)
  243. console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  244. // 每隔一段时间发一个心跳包保持连接状态
  245. this.keepAlive();
  246. })
  247. _socket.onClose((res) => {
  248. this.readyState = 'closed';
  249. //只要关闭就重连(暂时性处理)并且不是在后台 不进行重连
  250. if(this._reconnection && !Global.isOnHide ) {
  251. this.reconnect()
  252. }
  253. this.emit('close', res)
  254. console.log(`%c [Socket连接关闭: ${res}]`, this.logStyle)
  255. })
  256. _socket.onMessage((res) => {
  257. if(res.data != 1) {
  258. this.emit('message', res.data)
  259. }
  260. Global._socketCount += 1;
  261. if (Global._socketCount > 10000) {
  262. Global._socketCount = 2;
  263. }
  264. console.log(`%c [接收到Socket消息: ${JSON.stringify(res.data)}]`, this.logStyle);
  265. })
  266. _socket.onError((res) => {
  267. this.readyState = 'closed';
  268. if(this._reconnection && !Global.isOnHide) {
  269. this.reconnect()
  270. } else {
  271. _socket.close()
  272. }
  273. this.emit('error', res.errMsg);
  274. console.log(`%c [Socket错误: ${res.errMsg}]`, this.logStyle);
  275. })
  276. return _socket;
  277. }
  278. WsManager.prototype.openH5Connect = function() {
  279. let _socket = new WebSocket(this.url);
  280. _socket.binaryType = "arraybuffer";
  281. _socket.onopen = (event) => {
  282. this.readyState = 'open'
  283. this.emit('open', event)
  284. console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  285. // 每隔一段时间发一个心跳包保持连接状态
  286. this.keepAlive()
  287. }
  288. _socket.onclose = (event) => {
  289. this.readyState = 'closed';
  290. let code = event.code
  291. let reason = event.reason
  292. let wasClean = event.wasClean
  293. //只要关闭就重连(暂时性处理)
  294. if(this._reconnection) {
  295. this.reconnect()
  296. }
  297. this.emit('close', event)
  298. console.log(`%c [Socket连接关闭: ${reason}]`, this.logStyle)
  299. }
  300. _socket.onmessage = (event) => {
  301. if(event.data != 1) {
  302. this.emit('message', event.data)
  303. }
  304. console.log(`%c [接收到Socket消息: ${event.data}]`, this.logStyle);
  305. }
  306. _socket.onerror = (event) => {
  307. if(this._reconnection) {
  308. this.reconnect()
  309. } else {
  310. _socket.close()
  311. }
  312. this.emit(event)
  313. console.log(`%c [Socket错误: ${JSON.stringify(event)}]`, this.logStyle);
  314. }
  315. return _socket
  316. }
  317. WsManager.prototype.send = function(data) {
  318. console.log(`%c [发送Socket数据: ${data}]`, this.logStyle);
  319. if(CC_WECHATGAME) {
  320. let buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
  321. this.socket.send({
  322. data: buffer,
  323. success: function(res) {
  324. console.log('Success: ', JSON.stringify(res));
  325. },
  326. fail: function(res) {
  327. console.log('Fail: ', JSON.stringify(res));
  328. },
  329. complete: function(res) {
  330. console.log('Complete: ', JSON.stringify(res));
  331. }
  332. })
  333. } else {
  334. this.socket.binaryType = this.binaryType
  335. this.socket.send(data)
  336. }
  337. }
  338. // WsManager.prototype.onOpen = function(res) {
  339. // if(CC_WECHATGAME) {
  340. // this.socket.onOpen((res) => {
  341. // this.readyState = 'open'
  342. // callback && callback(res)
  343. // console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  344. // })
  345. // } else {
  346. // this.socket.onopen = () => {
  347. // this.readyState = 'open'
  348. // callback && callback()
  349. // console.log(`%c [Socket连接成功: ${this.url.split("&token")[0]}]`, this.logStyle);
  350. // }
  351. // }
  352. // }
  353. // WsManager.prototype.onClose = function(callback) {
  354. // if(CC_WECHATGAME) {
  355. // this.socket.onClose((res) => {
  356. // this.readyState = 'closed'
  357. // callback && callback(res)
  358. // console.log(`%c [Socket连接关闭: ${res}]`, this.logStyle)
  359. // })
  360. // } else {
  361. // this.socket.onclose = (event) => {
  362. // this.readyState = 'closed';
  363. // let code = event.code
  364. // let reason = event.reason
  365. // let wasClean = event.wasClean
  366. // callback && callback(event)
  367. // console.log(`%c [Socket连接关闭: ${reason}]`, this.logStyle)
  368. // }
  369. // }
  370. // }
  371. // WsManager.prototype.onMessage = function(callback) {
  372. // if(CC_WECHATGAME) {
  373. // this.socket.onMessage((res) => {
  374. // let data = res.data
  375. // callback && callback(data)
  376. // console.log(`%c [接收到Socket消息: ${JSON.stringify(data)}]`, this.logStyle);
  377. // })
  378. // } else {
  379. // this.socket.onmessage = (event) => {
  380. // let data = event.data
  381. // callback && callback(data)
  382. // console.log(`%c [接收到Socket消息: ${JSON.stringify(data)}]`, this.logStyle);
  383. // }
  384. // }
  385. // }
  386. // WsManager.prototype.onError = function(callback) {
  387. // if(CC_WECHATGAME) {
  388. // this.socket.onError((res) => {
  389. // callback && callback(res.errMsg)
  390. // console.log(`%c [Socket错误: ${res.errMsg}]`, this.logStyle);
  391. // })
  392. // } else {
  393. // this.socket.onerror = (event) => {
  394. // callback && callback(event.data)
  395. // console.log(`%c [Socket错误: ${event.data}]`, this.logStyle);
  396. // }
  397. // }
  398. // }
  399. /**
  400. * 配置socket连接超时时间
  401. * @param {Number} v 连接超时时间
  402. * @return {WsManager} WsManager对象实例
  403. * @api public
  404. */
  405. WsManager.prototype.timeout = function(v) {
  406. if(!arguments.length) {
  407. return this._timeout
  408. }
  409. this._timeout = v
  410. return this
  411. }
  412. /**
  413. * 自动重连配置
  414. * @param {Boolean} v 是否自动重连true / false
  415. * @return {WsManager} WsManager对象实例
  416. * @api public
  417. */
  418. WsManager.prototype.reconnection = function(v) {
  419. if(!arguments.length) {
  420. return this._reconnection
  421. }
  422. this._reconnection = !!v
  423. return this
  424. }
  425. /**
  426. * 配置最大重连次数
  427. * @param {Number} v 最大重连次数
  428. * @return {WsManager} WsManager对象实例
  429. * @api public
  430. */
  431. WsManager.prototype.reconnectionAttempts = function(v) {
  432. if (!arguments.length) {
  433. return this._reconnectionAttempts
  434. }
  435. this._reconnectionAttempts = v
  436. return this
  437. }
  438. module.exports = WsManager
  439. // var Ws = function() {
  440. // this.socket = new io(Api.SocketLocal, {
  441. // autoConnect: false, //自动连接
  442. // reconnection: true, //断开自动重连
  443. // reconnectionDelay: 2000, //自动重连时间,默认为2000毫秒
  444. // reconnectionAttempts: 10, //最大重连尝试次数,默认为Infinity
  445. // forceNew: true, //
  446. // })
  447. // this.socket.on("connect", () => {
  448. // console.log(`Socket connected: ${Api.SocketLocal}`);
  449. // })
  450. // }
  451. // Ws.prototype.open = function() {
  452. // this.socket.open()
  453. // }
  454. // /**
  455. // * 监听Websocket事件
  456. // * @param {String} eventName 监听事件名称
  457. // * @param {Function} callback 事件触发回调
  458. // */
  459. // Ws.prototype.on = function(eventName, callback) {
  460. // if(eventName) {
  461. // this.socket.on(eventName, data => {
  462. // console.log(`Socket On Event: ${eventName}`);
  463. // callback && callback(data)
  464. // })
  465. // }
  466. // }
  467. // /**
  468. // * 上报Websocket报文
  469. // * @param {String} eventName 上报事件名
  470. // * @param {Object} data 上报数据
  471. // */
  472. // Ws.prototype.emit = function(eventName, data) {
  473. // if(eventName) {
  474. // console.log(`Socket Do Emit: ${eventName}`, data);
  475. // this.socket.emit(eventName, data);
  476. // }
  477. // }
  478. // module.exports = new Ws();