Ws.js 15 KB

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