C端小程序
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

187 řádky
4.8 KiB

  1. let config = require("./config/config.js");
  2. const Http = require("./utils/HttpBasics");
  3. App({
  4. data: {},
  5. onLaunch: function(options) {
  6. console.log("onUnload ")
  7. var that = this;
  8. that.globalData.sceneAddress = options.scene;
  9. },
  10. /**
  11. * 获取地址位置信息
  12. */
  13. getLocation: function() {
  14. var that = this
  15. wx.getLocation({
  16. type: "wgs84",
  17. success: function(res) {
  18. that.globalData.locationInfo = res;
  19. },
  20. fail: error => {
  21. console.log(error);
  22. }
  23. });
  24. },
  25. globalData: {
  26. // token
  27. token: null,
  28. // user openId
  29. openId: null,
  30. // 渠道
  31. sceneAddress: null,
  32. // location info
  33. locationInfo: null,
  34. // 二维码参数
  35. scene: null,
  36. // 支持智慧停车, 用户名下有车
  37. phone: null,
  38. supportCar: false,
  39. parkVendor: 1, // 1: ETCP, 2: TJD
  40. // ETCP token
  41. etcpToken: null,
  42. carLogin: false,
  43. // 当前商场信息
  44. market: {
  45. name: "陕西大悦城"
  46. },
  47. // websocket
  48. socketClient: null,
  49. socketReceiver: function (e) { }, //收到消息回调
  50. },
  51. // 初始化websocket
  52. initSocket: function () {
  53. let that = this;
  54. // socket是否连接
  55. let socketConnected = false;
  56. // 待发送的消息队列
  57. let messageQueue = [];
  58. // 是否断线重连
  59. let reconnect = true;
  60. // 发送消息
  61. function sendSocketMessage(msg) {
  62. // console.log(msg);
  63. // 如果socket已连接则发送消息
  64. if (socketConnected) {
  65. wx.sendSocketMessage({
  66. data: msg
  67. })
  68. } else {
  69. // socket没有连接将消息放入队列中
  70. messageQueue.push(msg);
  71. }
  72. }
  73. // 关闭连接
  74. function close() {
  75. if (socketConnected) {
  76. wx.closeSocket()
  77. socketConnected = false;
  78. }
  79. }
  80. // 符合WebSocket定义的对象
  81. var ws = {
  82. send: sendSocketMessage,
  83. close: close
  84. }
  85. // 创建一个 WebSocket 连接
  86. function connect() {
  87. wx.connectSocket({
  88. url: config.wsurl,
  89. header: {
  90. token: that.globalData.token //从服务端获取一个token,服务端验证token是否允许连接,案例中没做限制
  91. }
  92. })
  93. }
  94. connect();
  95. // 监听 WebSocket 连接打开事件
  96. wx.onSocketOpen(function (res) {
  97. console.log("WebSocket 连接成功")
  98. socketConnected = true;
  99. ws.onopen();
  100. // 连接成功后,将队列中的消息发送出去
  101. let queueLength = messageQueue.length
  102. for (let i = 0; i < queueLength; i++) {
  103. sendSocketMessage(messageQueue.shift())
  104. }
  105. })
  106. // 监听 WebSocket 接受到服务器的消息事件
  107. wx.onSocketMessage(function (res) {
  108. ws.onmessage(res);
  109. })
  110. // 监听 WebSocket 错误事件
  111. wx.onSocketError(function (res) {
  112. console.log("WebSocket 错误事件")
  113. if (!socketConnected) {
  114. // 断线重连
  115. if (reconnect) {
  116. connect();
  117. }
  118. }
  119. })
  120. // 监听 WebSocket 连接关闭事件
  121. wx.onSocketClose(function (res) {
  122. console.log("WebSocket 连接关闭")
  123. socketConnected = false;
  124. // 断线重连
  125. if (reconnect) {
  126. connect();
  127. }
  128. })
  129. const Stomp = require('/utils/stomp.min.js').Stomp;
  130. /**
  131. * 定期发送心跳或检测服务器心跳
  132. * The heart-beating is using window.setInterval() to regularly send heart-beats and/or check server heart-beats.
  133. * 可看stomp.js的源码(195,207,489行),由于小程序没有window对象,所以我们要调用小程序的定时器api实现
  134. */
  135. Stomp.setInterval = function (interval, f) {
  136. return setInterval(f, interval);
  137. };
  138. // 结束定时器的循环调用
  139. Stomp.clearInterval = function (id) {
  140. return clearInterval(id);
  141. };
  142. const stompClient = Stomp.over(ws);
  143. that.globalData.socketClient = stompClient;
  144. stompClient.connect({}, function (callback) {
  145. // 订阅自己的
  146. stompClient.subscribe('/user/'+that.globalData.openId+'/message', function (message, headers) {
  147. console.log('收到只发送给我的消息:', message);
  148. that.globalData.socketReceiver(JSON.parse(message.body));
  149. // 通知服务端收到消息
  150. message.ack();
  151. });
  152. stompClient.subscribe('/topic/1001A', function (message, headers) {
  153. console.log('收到TOPIC的消息:', message);
  154. that.globalData.socketReceiver(JSON.parse(message.body));
  155. // 通知服务端收到消息
  156. //message.ack();
  157. });
  158. // 向服务端发送消息
  159. stompClient.send("/app/message", {}, JSON.stringify({
  160. 'msg': 'client: ' + that.globalData.openId
  161. }));
  162. })
  163. },
  164. //统一发送消息
  165. sendSocketMessage: function (msg) {
  166. this.globalData.socketClient.send("/app/message", {}, JSON.stringify(msg));
  167. }
  168. });