No Description

client.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. return new (P || (P = Promise))(function (resolve, reject) {
  4. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  7. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8. });
  9. };
  10. var __generator = (this && this.__generator) || function (thisArg, body) {
  11. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  12. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  13. function verb(n) { return function (v) { return step([n, v]); }; }
  14. function step(op) {
  15. if (f) throw new TypeError("Generator is already executing.");
  16. while (_) try {
  17. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  18. if (y = 0, t) op = [op[0] & 2, t.value];
  19. switch (op[0]) {
  20. case 0: case 1: t = op; break;
  21. case 4: _.label++; return { value: op[1], done: false };
  22. case 5: _.label++; y = op[1]; op = [0]; continue;
  23. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  24. default:
  25. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  26. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  27. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  28. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  29. if (t[2]) _.ops.pop();
  30. _.trys.pop(); continue;
  31. }
  32. op = body.call(thisArg, _);
  33. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  34. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  35. }
  36. };
  37. Object.defineProperty(exports, "__esModule", { value: true });
  38. var packet_1 = require("./packet");
  39. var utils_1 = require("./utils");
  40. var error_1 = require("./error");
  41. var clientError = 400;
  42. var Client = (function () {
  43. function Client(url, readyStateCallback) {
  44. this.listeners = new Map();
  45. this.requestHeader = '';
  46. this.requestHeader = '';
  47. this._maxPayload = 1024 * 1024;
  48. this.url = url;
  49. this.reconnectTimes = 0;
  50. this.readyStateCallback = readyStateCallback;
  51. this._enableLogger = false;
  52. this.socket = this.connect();
  53. }
  54. Object.defineProperty(Client.prototype, "maxPayload", {
  55. get: function () {
  56. return this._maxPayload;
  57. },
  58. set: function (maxPayload) {
  59. this._maxPayload = maxPayload;
  60. },
  61. enumerable: true,
  62. configurable: true
  63. });
  64. Object.defineProperty(Client.prototype, "enableLogger", {
  65. get: function () {
  66. return this._enableLogger;
  67. },
  68. set: function (enableLogger) {
  69. this._enableLogger = enableLogger;
  70. },
  71. enumerable: true,
  72. configurable: true
  73. });
  74. Client.prototype.ping = function (param) {
  75. return __awaiter(this, void 0, void 0, function () {
  76. var _this = this;
  77. return __generator(this, function (_a) {
  78. return [2, new Promise(function (resolve, reject) {
  79. if (_this.socket.readyState !== _this.socket.OPEN) {
  80. if (_this._enableLogger) {
  81. console.log('[ping]: connection refuse');
  82. }
  83. reject(new error_1.WebsocketError(clientError, 'connection refuse'));
  84. }
  85. var heartbeatOperator = 0;
  86. _this.listeners.set(heartbeatOperator, function (data) {
  87. var code = _this.getResponseProperty('code');
  88. if (code !== '') {
  89. var message = _this.getResponseProperty('message');
  90. reject(new error_1.WebsocketError(Number(code), message));
  91. }
  92. else {
  93. resolve(data);
  94. }
  95. });
  96. var p = new packet_1.Packet();
  97. _this.send(p.pack(heartbeatOperator, 0, _this.requestHeader, JSON.stringify(param)));
  98. if (_this._enableLogger) {
  99. console.info('[send data packet]', heartbeatOperator, 0, _this.requestHeader, param);
  100. }
  101. })];
  102. });
  103. });
  104. };
  105. Client.prototype.request = function (operator, param) {
  106. return __awaiter(this, void 0, void 0, function () {
  107. return __generator(this, function (_a) {
  108. switch (_a.label) {
  109. case 0: return [4, this.asyncSend(operator, param)];
  110. case 1: return [2, _a.sent()];
  111. }
  112. });
  113. });
  114. };
  115. Client.prototype.addMessageListener = function (operator, listener) {
  116. this.listeners.set(utils_1.Utils.crc32(operator), listener);
  117. };
  118. Client.prototype.removeMessageListener = function (operator) {
  119. delete this.listeners[utils_1.Utils.crc32(operator)];
  120. };
  121. Object.defineProperty(Client.prototype, "readyState", {
  122. get: function () {
  123. return this.socket.readyState;
  124. },
  125. enumerable: true,
  126. configurable: true
  127. });
  128. Client.prototype.setRequestProperty = function (key, value) {
  129. var v = this.getRequestProperty(key);
  130. this.requestHeader = this.requestHeader.replace(key + '=' + v + ';', '');
  131. this.requestHeader = this.requestHeader + key + '=' + value + ';';
  132. };
  133. Client.prototype.getRequestProperty = function (key) {
  134. if (this.requestHeader !== undefined) {
  135. var values = this.requestHeader.split(';');
  136. for (var index in values) {
  137. var kv = values[index].split('=');
  138. if (kv[0] === key) {
  139. return kv[1];
  140. }
  141. }
  142. }
  143. return '';
  144. };
  145. Client.prototype.setResponseProperty = function (key, value) {
  146. var v = this.getResponseProperty(key);
  147. this.responseHeader = this.responseHeader.replace(key + '=' + v + ';', '');
  148. this.responseHeader = this.responseHeader + key + '=' + value + ';';
  149. };
  150. Client.prototype.getResponseProperty = function (key) {
  151. if (this.responseHeader !== undefined) {
  152. var values = this.responseHeader.split(';');
  153. for (var index in values) {
  154. var kv = values[index].split('=');
  155. if (kv[0] === key) {
  156. return kv[1];
  157. }
  158. }
  159. }
  160. return '';
  161. };
  162. Client.prototype.connect = function () {
  163. var _this = this;
  164. var readyStateCallback = this.readyStateCallback;
  165. var ws = new WebSocket(this.url);
  166. ws.binaryType = 'blob';
  167. ws.onopen = function (ev) {
  168. if (_this._enableLogger) {
  169. console.info('[websocket] open connection');
  170. }
  171. _this.reconnectTimes = 0;
  172. readyStateCallback.onOpen(ev);
  173. };
  174. ws.onclose = function (ev) {
  175. if (_this._enableLogger) {
  176. console.info('[websocket] close connection');
  177. }
  178. _this.reconnect();
  179. readyStateCallback.onClose(ev);
  180. };
  181. ws.onerror = function (ev) {
  182. if (_this._enableLogger) {
  183. console.info('[websocket] error');
  184. }
  185. _this.reconnect();
  186. readyStateCallback.onError(ev);
  187. };
  188. ws.onmessage = function (ev) {
  189. if (ev.data instanceof Blob) {
  190. var reader_1 = new FileReader();
  191. reader_1.readAsArrayBuffer(ev.data);
  192. reader_1.onload = function () {
  193. try {
  194. var packet = new packet_1.Packet().unPack(reader_1.result);
  195. var packetLength = packet.headerLength + packet.bodyLength + 20;
  196. if (packetLength > _this._maxPayload) {
  197. throw new Error('the packet is big than ' + _this._maxPayload);
  198. }
  199. var operator = Number(packet.operator) + Number(packet.sequence);
  200. if (_this.listeners.has(operator)) {
  201. if (packet.body === '') {
  202. packet.body = '{}';
  203. }
  204. _this.responseHeader = packet.header;
  205. _this.listeners.get(operator)(JSON.parse(packet.body));
  206. }
  207. if (_this._enableLogger) {
  208. if (operator !== 0 && packet.body !== 'null') {
  209. console.info('receive data packet', packet.body);
  210. }
  211. }
  212. }
  213. catch (e) {
  214. throw new Error(e);
  215. }
  216. };
  217. }
  218. else {
  219. throw new Error('unsupported data format');
  220. }
  221. };
  222. return ws;
  223. };
  224. Client.prototype.reconnect = function () {
  225. var _this = this;
  226. if (!this.reconnectLock) {
  227. this.reconnectLock = true;
  228. if (this._enableLogger) {
  229. console.info('websocket reconnect in ' + this.reconnectTimes + 's');
  230. }
  231. setTimeout(function () {
  232. _this.reconnectTimes++;
  233. _this.socket = _this.connect();
  234. _this.reconnectLock = false;
  235. }, this.reconnectTimes * 1000);
  236. }
  237. };
  238. Client.prototype.send = function (data) {
  239. if (this.socket.readyState !== this.socket.OPEN) {
  240. if (this._enableLogger) {
  241. console.error('[send] WebSocket is already in CLOSING or CLOSED state.');
  242. }
  243. return;
  244. }
  245. try {
  246. this.socket.send(data);
  247. }
  248. catch (e) {
  249. throw new Error('send data error' + e);
  250. }
  251. };
  252. Client.prototype.asyncSend = function (operator, param) {
  253. var _this = this;
  254. return new Promise(function (resolve, reject) {
  255. if (_this.socket.readyState !== _this.socket.OPEN) {
  256. if (_this._enableLogger) {
  257. console.log('[ping]: connection refuse');
  258. }
  259. reject(new error_1.WebsocketError(clientError, 'asyncSend: connection refuse'));
  260. }
  261. var sequence = new Date().getTime();
  262. var listener = utils_1.Utils.crc32(operator) + sequence;
  263. _this.listeners.set(listener, function (data) {
  264. var code = _this.getResponseProperty('code');
  265. if (code !== '') {
  266. var message = _this.getResponseProperty('message');
  267. reject(new error_1.WebsocketError(Number(code), message));
  268. }
  269. else {
  270. resolve(data);
  271. }
  272. delete _this.listeners[listener];
  273. });
  274. var p = new packet_1.Packet();
  275. _this.send(p.pack(utils_1.Utils.crc32(operator), sequence, _this.requestHeader, JSON.stringify(param)));
  276. if (_this._enableLogger) {
  277. console.info('[send data packet]', operator, sequence, _this.requestHeader, param);
  278. }
  279. });
  280. };
  281. return Client;
  282. }());
  283. exports.Client = Client;
  284. var client;
  285. function getClient(url, callback) {
  286. if (!client) {
  287. client = new Client(url, callback);
  288. }
  289. return client;
  290. }
  291. exports.getClient = getClient;