WeChat_Dev.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. var rpc_client_id, Hlclient = function (wsURL) {
  2. this.wsURL = wsURL;
  3. this.handlers = {
  4. _execjs: function (resolve, param) {
  5. var res = eval(param)
  6. resolve(res || "没有返回值")
  7. }
  8. };
  9. this.socket = undefined;
  10. this.isWechat = typeof wx !== 'undefined'; // 新增环境判断
  11. if (!wsURL) throw new Error('wsURL can not be empty!!');
  12. // 微信环境读取持久化的clientId
  13. if (this.isWechat && wx.getStorageSync('rpc_client_id')) {
  14. rpc_client_id = wx.getStorageSync('rpc_client_id');
  15. }
  16. this.connect();
  17. }
  18. Hlclient.prototype.connect = function () {
  19. var _this = this;
  20. // 处理clientId参数
  21. if (this.wsURL.indexOf("clientId=") === -1 && rpc_client_id) {
  22. this.wsURL += "&clientId=" + rpc_client_id;
  23. }
  24. console.log('begin connect to:', this.wsURL);
  25. try {
  26. if (this.isWechat) {
  27. // 微信环境使用wx API
  28. this.socket = wx.connectSocket({
  29. url: this.wsURL,
  30. success() {
  31. console.log('微信WS连接建立成功');
  32. },
  33. fail(err) {
  34. console.error('微信WS连接失败:', err);
  35. _this.reconnect();
  36. }
  37. });
  38. // 微信事件监听
  39. wx.onSocketMessage(function (res) {
  40. _this.handlerRequest(res.data);
  41. });
  42. wx.onSocketOpen(function () {
  43. console.log("rpc连接成功");
  44. });
  45. wx.onSocketError(function (err) {
  46. console.error('rpc连接出错:', err);
  47. });
  48. wx.onSocketClose(function () {
  49. console.log('rpc连接关闭');
  50. _this.reconnect();
  51. });
  52. } else {
  53. // 浏览器环境
  54. this.socket = new WebSocket(this.wsURL);
  55. this.socket.onmessage = function (e) {
  56. _this.handlerRequest(e.data);
  57. }
  58. this.socket.onclose = function () {
  59. console.log('rpc已关闭');
  60. _this.reconnect();
  61. }
  62. this.socket.addEventListener('open', () => {
  63. console.log("rpc连接成功");
  64. });
  65. this.socket.addEventListener('error', (err) => {
  66. console.error('rpc连接出错:', err);
  67. });
  68. }
  69. } catch (e) {
  70. console.log("connection failed:", e);
  71. this.reconnect();
  72. }
  73. };
  74. Hlclient.prototype.reconnect = function () {
  75. console.log("10秒后尝试重连...");
  76. var _this = this;
  77. setTimeout(function () {
  78. _this.connect();
  79. }, 10000);
  80. };
  81. Hlclient.prototype.send = function (msg) {
  82. if (this.isWechat) {
  83. // 微信环境发送消息
  84. if (this.socket && this.socket.readyState === 1) {
  85. wx.sendSocketMessage({
  86. data: msg,
  87. fail(err) {
  88. console.error('消息发送失败:', err);
  89. }
  90. });
  91. }
  92. } else {
  93. // 浏览器环境
  94. if (this.socket.readyState === WebSocket.OPEN) {
  95. this.socket.send(msg);
  96. }
  97. }
  98. };
  99. Hlclient.prototype.regAction = function (func_name, func) {
  100. if (typeof func_name !== 'string') throw new Error("func_name must be string");
  101. if (typeof func !== 'function') throw new Error("must be function");
  102. console.log("register func:", func_name);
  103. this.handlers[func_name] = func;
  104. return true;
  105. };
  106. Hlclient.prototype.handlerRequest = function (requestJson) {
  107. var _this = this;
  108. try {
  109. var result = JSON.parse(requestJson);
  110. // 微信环境持久化clientId
  111. if (result["registerId"]) {
  112. rpc_client_id = result['registerId'];
  113. if (this.isWechat) {
  114. wx.setStorageSync('rpc_client_id', rpc_client_id);
  115. }
  116. return;
  117. }
  118. if (!result['action'] || !result["message_id"]) {
  119. console.warn('Invalid request:', result);
  120. return;
  121. }
  122. var action = result["action"],
  123. message_id = result["message_id"],
  124. param = result["param"];
  125. try { param = JSON.parse(param); } catch (e) { }
  126. var handler = this.handlers[action];
  127. if (!handler) {
  128. return this.sendResult(action, message_id, 'Action not found');
  129. }
  130. handler(function (response) {
  131. _this.sendResult(action, message_id, response);
  132. }, param);
  133. } catch (error) {
  134. console.log("处理请求出错:", error);
  135. this.sendResult(action, message_id, error.message);
  136. }
  137. };
  138. Hlclient.prototype.sendResult = function (action, message_id, data) {
  139. if (typeof data === 'object') {
  140. try { data = JSON.stringify(data); } catch (e) { }
  141. }
  142. var response = JSON.stringify({
  143. action: action,
  144. message_id: message_id,
  145. response_data: data
  146. });
  147. this.send(response);
  148. };