Ws.js 15 KB

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