WxSocketTransport.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. var __assign = (this && this.__assign) || function () {
  4. __assign = Object.assign || function(t) {
  5. for (var s, i = 1, n = arguments.length; i < n; i++) {
  6. s = arguments[i];
  7. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  8. t[p] = s[p];
  9. }
  10. return t;
  11. };
  12. return __assign.apply(this, arguments);
  13. };
  14. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  15. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  16. return new (P || (P = Promise))(function (resolve, reject) {
  17. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  18. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  19. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  20. step((generator = generator.apply(thisArg, _arguments || [])).next());
  21. });
  22. };
  23. var __generator = (this && this.__generator) || function (thisArg, body) {
  24. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  25. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  26. function verb(n) { return function (v) { return step([n, v]); }; }
  27. function step(op) {
  28. if (f) throw new TypeError("Generator is already executing.");
  29. while (_) try {
  30. 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;
  31. if (y = 0, t) op = [op[0] & 2, t.value];
  32. switch (op[0]) {
  33. case 0: case 1: t = op; break;
  34. case 4: _.label++; return { value: op[1], done: false };
  35. case 5: _.label++; y = op[1]; op = [0]; continue;
  36. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  37. default:
  38. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  39. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  40. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  41. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  42. if (t[2]) _.ops.pop();
  43. _.trys.pop(); continue;
  44. }
  45. op = body.call(thisArg, _);
  46. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  47. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  48. }
  49. };
  50. import { LogLevel } from "./ILogger";
  51. import { Arg, getDataDetail } from "./Utils";
  52. import { WxSocketReadyState } from "./Polyfills";
  53. import { isVersionSupport } from "./WechatVersionDiff";
  54. /**
  55. * 微信 sosocket 数据传输
  56. * @description 整体重写了这部分websocket支持,逻辑这样看起来合理一些
  57. */
  58. var WxSocketTransport = /** @class */ (function () {
  59. function WxSocketTransport(options) {
  60. this.readyState = WxSocketReadyState.CONNECTING;
  61. this.logger = options.logger;
  62. this.accessTokenFactory = options.accessTokenFactory;
  63. this.socketUrlFactory = options.socketUrlFactory;
  64. this.logMessageContent = options.logMessageContent;
  65. this.onreceive = null;
  66. this.onclose = null;
  67. this.allowReplaceSocket = options.allowReplaceSocket;
  68. this.timeout = options.timeout ? options.timeout : 60 * 1000;
  69. this.delayTime = options.delayTime ? options.delayTime : 100;
  70. if (options.enableMessageQueue) {
  71. this.enableMessageQueue = true;
  72. this.messageQueue = [];
  73. }
  74. else {
  75. this.enableMessageQueue = false;
  76. }
  77. if (options.reconnect) {
  78. this.reconnect = {
  79. enable: options.reconnect.enable == true ? true : false,
  80. max: options.reconnect.max ? options.reconnect.max : 3,
  81. val: 0
  82. };
  83. }
  84. else {
  85. this.reconnect = {
  86. enable: false,
  87. max: 3,
  88. val: 0
  89. };
  90. }
  91. }
  92. WxSocketTransport.prototype.connect = function (options) {
  93. return __awaiter(this, void 0, void 0, function () {
  94. var replacedUrl, token;
  95. var _this = this;
  96. return __generator(this, function (_a) {
  97. switch (_a.label) {
  98. case 0:
  99. // vali is exists
  100. Arg.isRequired(options, "options");
  101. // vali url is support by wechat
  102. Arg.validationUrlIsSupportByWechat(options.url);
  103. this.connectOptions = options; // 连接参数缓存
  104. this.logger.log(LogLevel.Trace, "(WebSockets transport) Connecting.");
  105. if (!this.socketUrlFactory) return [3 /*break*/, 2];
  106. return [4 /*yield*/, this.socketUrlFactory(options.url)];
  107. case 1:
  108. replacedUrl = _a.sent();
  109. if (replacedUrl) {
  110. options.url = replacedUrl;
  111. }
  112. return [3 /*break*/, 4];
  113. case 2:
  114. if (!this.accessTokenFactory) return [3 /*break*/, 4];
  115. return [4 /*yield*/, this.accessTokenFactory()];
  116. case 3:
  117. token = _a.sent();
  118. this.logger.log(LogLevel.Debug, "getted token:", token);
  119. if (token) {
  120. options.url += (options.url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token));
  121. }
  122. _a.label = 4;
  123. case 4: return [2 /*return*/, new Promise(function (resolve, reject) {
  124. // 忽略url修正,因为传入错误url的话,将直接抛出异常
  125. options.url = options.url.replace(/^http/, "ws");
  126. // 这里执行的是连接操socket的逻辑
  127. var socketTask;
  128. // 1.7.0 及以上版本,最多可以同时存在 5 个 WebSocket 连接, 以下版本,一个小程序同时只能有一个 WebSocket 连接,如果当前已存在一个 WebSocket 连接,会自动关闭该连接,并重新创建一个 WebSocket 连接
  129. var supportCount = isVersionSupport("1.7.0") ? 5 : 1;
  130. if (supportCount <= WxSocketTransport.count && !_this.allowReplaceSocket) {
  131. // 抛出异常, 并return
  132. reject({
  133. errMsg: "Maximum connections|" + WxSocketTransport.count
  134. });
  135. return;
  136. }
  137. else if (WxSocketTransport.count == 5) {
  138. // 抛出异常, 并return
  139. reject({
  140. errMsg: "Maximum connections|" + WxSocketTransport.count
  141. });
  142. return;
  143. }
  144. if (!socketTask) {
  145. socketTask = wx.connectSocket(__assign({
  146. // 传入 两个默认的 回调,当然也可以在 options 里面覆盖 使用自定义回调.
  147. success: function (res) {
  148. _this.logger.log(LogLevel.Debug, "wx.connectSocket():success");
  149. }, fail: function (res) {
  150. _this.logger.log(LogLevel.Debug, "wx.connectSocket():fail");
  151. reject(res);
  152. } }, options));
  153. }
  154. // ! 因为小程序两种协议都支持,所以不需要指定特定的 binaryType
  155. /** 连接成功处理 */
  156. socketTask.onOpen(function (result) { return __awaiter(_this, void 0, void 0, function () {
  157. var _i, _a, msg;
  158. return __generator(this, function (_b) {
  159. switch (_b.label) {
  160. case 0:
  161. this.logger.log(LogLevel.Information, "websocket\u8FDE\u63A5\u5EFA\u7ACB " + (this.logMessageContent ? "wx api:[" + options.url + "]" : ""));
  162. this.logger.log(LogLevel.Debug, "wx.connectSocket success message:", result);
  163. WxSocketTransport.count += 1;
  164. this.readyState = WxSocketReadyState.OPEN;
  165. this.socketTask = socketTask;
  166. // 等待回调执行完成后,再重新队列中消息
  167. return [4 /*yield*/, resolve()];
  168. case 1:
  169. // 等待回调执行完成后,再重新队列中消息
  170. _b.sent();
  171. if (!(this.enableMessageQueue && this.messageQueue.length > 0)) return [3 /*break*/, 5];
  172. _i = 0, _a = this.messageQueue;
  173. _b.label = 2;
  174. case 2:
  175. if (!(_i < _a.length)) return [3 /*break*/, 5];
  176. msg = _a[_i];
  177. this.logger.log(LogLevel.Debug, "\u63A8\u9001\u79BB\u7EBF\u6D88\u606F", this.logMessageContent ? msg : "");
  178. return [4 /*yield*/, this.send(msg)];
  179. case 3:
  180. _b.sent();
  181. _b.label = 4;
  182. case 4:
  183. _i++;
  184. return [3 /*break*/, 2];
  185. case 5: return [2 /*return*/];
  186. }
  187. });
  188. }); });
  189. /** 建立连接出错处理 */
  190. socketTask.onError(function (res) {
  191. _this.readyState = WxSocketReadyState.CLOSED;
  192. reject(res);
  193. });
  194. /** 接收到消息处理 */
  195. socketTask.onMessage(function (res) {
  196. _this.logger.log(LogLevel.Trace, "(WebSockets transport) data received.", getDataDetail(res.data, _this.logMessageContent));
  197. if (_this.onreceive) {
  198. _this.onreceive(res.data);
  199. }
  200. });
  201. socketTask.onClose(function (res) { return _this.close(res); });
  202. })];
  203. }
  204. });
  205. });
  206. };
  207. /** 休眠 */
  208. WxSocketTransport.prototype.delay = function () {
  209. var _this = this;
  210. return new Promise(function (resolve) {
  211. // ! 由于小程序机制,所以需要手工清理timer
  212. var timer = setTimeout(function () {
  213. clearTimeout(timer);
  214. resolve();
  215. }, _this.delayTime);
  216. });
  217. };
  218. /** 发送 */
  219. WxSocketTransport.prototype.send = function (data) {
  220. return __awaiter(this, void 0, void 0, function () {
  221. var loop;
  222. var _this = this;
  223. return __generator(this, function (_a) {
  224. switch (_a.label) {
  225. case 0:
  226. if (!(this.socketTask && this.readyState === WxSocketReadyState.OPEN)) return [3 /*break*/, 1];
  227. this.logger.log(LogLevel.Trace, "[WxSocket] \u63A8\u9001\u6570\u636E.", getDataDetail(data, this.logMessageContent));
  228. return [2 /*return*/, new Promise(function (resolve, reject) {
  229. _this.socketTask.send({
  230. data: data,
  231. success: function () { return resolve(); },
  232. fail: function () { return reject(); }
  233. });
  234. })];
  235. case 1:
  236. if (!this.enableMessageQueue) return [3 /*break*/, 5];
  237. this.messageQueue.push(data);
  238. loop = 0;
  239. _a.label = 2;
  240. case 2:
  241. if (!(this.socketTask && this.readyState !== WxSocketReadyState.OPEN)) return [3 /*break*/, 4];
  242. return [4 /*yield*/, this.delay()];
  243. case 3:
  244. _a.sent();
  245. loop += this.delayTime;
  246. if (loop >= this.timeout) {
  247. // 超时设置
  248. return [2 /*return*/, Promise.reject({
  249. errMsg: "WebSocket connect timeout."
  250. })];
  251. }
  252. return [3 /*break*/, 2];
  253. case 4:
  254. // 回调
  255. return [2 /*return*/, this.send(data)];
  256. case 5: return [2 /*return*/, Promise.reject({
  257. errMsg: "WebSocket is not in the OPEN state"
  258. })];
  259. }
  260. });
  261. });
  262. };
  263. /** 停止 */
  264. WxSocketTransport.prototype.stop = function (msg) {
  265. var _this = this;
  266. return new Promise(function (resolve, reject) {
  267. if (_this.socketTask) {
  268. _this.socketTask.close({
  269. code: 1000,
  270. reason: "stop socket",
  271. success: function (res) { return resolve(msg || res); },
  272. fail: function (res) { return reject(res); }
  273. });
  274. }
  275. });
  276. };
  277. /**
  278. * 连接断开处理
  279. * @param res
  280. */
  281. WxSocketTransport.prototype.close = function (res) {
  282. // webSocket will be null if the transport did not start successfully
  283. this.logger.log(LogLevel.Trace, "(WebSockets transport) socket closed.");
  284. WxSocketTransport.count = WxSocketTransport.count > 0 ? WxSocketTransport.count - 1 : 0;
  285. if (this.onclose) {
  286. if (res && res.code !== 1000) {
  287. this.onclose(new Error("WebSocket closed with status code: " + res.code + " (" + res.reason + ")."));
  288. }
  289. else {
  290. this.onclose();
  291. }
  292. }
  293. };
  294. /**
  295. * 静态变量 - 表示当前是否有正在连接中的socket
  296. */
  297. WxSocketTransport.count = 0;
  298. return WxSocketTransport;
  299. }());
  300. export { WxSocketTransport };