ws.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. "use strict";
  2. function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }
  3. function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
  4. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  5. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  6. function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  8. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  9. var Ws = /*#__PURE__*/function () {
  10. function Ws(ws, data) {
  11. var _this = this;
  12. _classCallCheck(this, Ws);
  13. // [{url, data, method...},,,,]
  14. this._ws = ws;
  15. this._data = data; // 待发送的消息列
  16. this._msgs = [];
  17. this.socket = this.doLink();
  18. this.doOpen(); // 订阅/发布模型
  19. this._events = {}; // 是否保持连接
  20. this._isLink = true; // 循环检查
  21. setInterval(function () {
  22. if (_this._isLink) {
  23. if (_this.socket.readyState == 2 || _this.socket.readyState == 3) {
  24. _this.resetLink();
  25. }
  26. }
  27. }, 3000);
  28. } // 重连
  29. _createClass(Ws, [{
  30. key: "resetLink",
  31. value: function resetLink() {
  32. this.socket = this.doLink();
  33. this.doOpen();
  34. } // 连接
  35. }, {
  36. key: "doLink",
  37. value: function doLink() {
  38. var ws = new WebSocket( this._ws);
  39. return ws;
  40. }
  41. }, {
  42. key: "doOpen",
  43. value: function doOpen() {
  44. var _this2 = this;
  45. this.socket.addEventListener('open',function (ev) {
  46. _this2.onOpen(ev);
  47. });
  48. this.socket.addEventListener('message',function (ev) {
  49. _this2.onMessage(ev);
  50. });
  51. this.socket.addEventListener('close',function (ev) {
  52. _this2.onClose(ev);
  53. });
  54. this.socket.addEventListener('error',function (ev) {
  55. _this2.onError(ev);
  56. });
  57. } // 打开
  58. }, {
  59. key: "onOpen",
  60. value: function onOpen() {
  61. var _this3 = this;
  62. // 打开时重发未发出的消息
  63. var list = Object.assign([], this._msgs);
  64. list.forEach(function (item) {
  65. if (_this3.send(item)) {
  66. var idx = _this3._msgs.indexOf(item);
  67. if (idx != -1) {
  68. _this3._msgs.splice(idx, 1);
  69. }
  70. }
  71. });
  72. } // 手动关闭
  73. }, {
  74. key: "doClose",
  75. value: function doClose() {
  76. this._isLink = false;
  77. this._events = {};
  78. this._msgs = [];
  79. this.socket.close({
  80. success: function success() {
  81. console.log('socket close success');
  82. }
  83. });
  84. } // 添加监听
  85. }, {
  86. key: "on",
  87. value: function on(name, handler) {
  88. this.subscribe(name, handler);
  89. } // 取消监听
  90. }, {
  91. key: "off",
  92. value: function off(name, handler) {
  93. this.unsubscribe(name, handler);
  94. } // 关闭事件
  95. }, {
  96. key: "onClose",
  97. value: function onClose() {
  98. var _this4 = this;
  99. // 是否重新连接
  100. if (this._isLink) {
  101. setTimeout(function () {
  102. _this4.resetLink();
  103. }, 3000);
  104. }
  105. } // 错误
  106. }, {
  107. key: "onError",
  108. value: function onError(evt) {
  109. this.Notify({
  110. Event: 'error',
  111. Data: evt
  112. });
  113. } // 接受数据
  114. }, {
  115. key: "onMessage",
  116. value: function onMessage(evt) {
  117. try {
  118. // 解析推送的数据
  119. var data = JSON.parse(evt.data); // 通知订阅者
  120. this.Notify({
  121. Event: 'message',
  122. Data: data
  123. });
  124. } catch (err) {
  125. console.error(' >> Data parsing error:', err); // 通知订阅者
  126. this.Notify({
  127. Event: 'error',
  128. Data: err
  129. });
  130. }
  131. } // 订阅事件的方法
  132. }, {
  133. key: "subscribe",
  134. value: function subscribe(name, handler) {
  135. if (this._events.hasOwnProperty(name)) {
  136. this._events[name].push(handler); // 追加事件
  137. } else {
  138. this._events[name] = [handler]; // 添加事件
  139. }
  140. } // 取消订阅事件
  141. }, {
  142. key: "unsubscribe",
  143. value: function unsubscribe(name, handler) {
  144. var start = this._events[name].findIndex(function (item) {
  145. return item === handler;
  146. }); // 删除该事件
  147. this._events[name].splice(start, 1);
  148. } // 发布后通知订阅者
  149. }, {
  150. key: "Notify",
  151. value: function Notify(entry) {
  152. // 检查是否有订阅者 返回队列
  153. var cbQueue = this._events[entry.Event];
  154. if (cbQueue && cbQueue.length) {
  155. var _iterator = _createForOfIteratorHelper(cbQueue),
  156. _step;
  157. try {
  158. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  159. var callback = _step.value;
  160. if (_instanceof(callback, Function)) callback(entry.Data);
  161. }
  162. } catch (err) {
  163. _iterator.e(err);
  164. } finally {
  165. _iterator.f();
  166. }
  167. }
  168. } // 发送消息
  169. }, {
  170. key: "send",
  171. value: function send(data) {
  172. if (this.socket.readyState == 1) {
  173. this.socket.send(JSON.stringify(data));
  174. return true;
  175. } else {
  176. // 保存到待发送信息
  177. if (!this._msgs.includes(data)) {
  178. this._msgs.push(data);
  179. }
  180. ;
  181. return false;
  182. }
  183. }
  184. }]);
  185. return Ws;
  186. }();
  187. window.Ws = Ws;