websocket.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // socket已经连接成功
  2. var socketOpen = false
  3. // socket已经调用关闭function
  4. var socketClose = false
  5. // socket发送的消息队列
  6. var socketMsgQueue = []
  7. // 判断心跳变量
  8. var heart = ''
  9. // 心跳失败次数
  10. var heartBeatFailCount = 0
  11. // 终止心跳
  12. var heartBeatTimeOut = null;
  13. // 终止重新连接
  14. var connectSocketTimeOut = null;
  15. var webSocket = {
  16. /**
  17. * 创建一个 WebSocket 连接
  18. * @param {options}
  19. * url String 是 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
  20. * header Object 否 HTTP Header , header 中不能设置 Referer
  21. * method String 否 默认是GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  22. * protocols StringArray 否 子协议数组 1.4.0
  23. * success Function 否 接口调用成功的回调函数
  24. * fail Function 否 接口调用失败的回调函数
  25. * complete Function 否 接口调用结束的回调函数(调用成功、失败都会执行)
  26. */
  27. connectSocket: function (options) {
  28. socketOpen = false
  29. socketClose = false
  30. socketMsgQueue = []
  31. wx.connectSocket({
  32. url: 'wss://xiaochengxuapi.jrjyjrjy.com/ws',
  33. success: function (res) {
  34. if (options) {
  35. // 成功回调
  36. options.success && options.success(res);
  37. }
  38. },
  39. fail: function (res) {
  40. if (options) {
  41. // 失败回调
  42. options.fail && options.fail(res);
  43. }
  44. }
  45. })
  46. },
  47. /**
  48. * 通过 WebSocket 连接发送数据
  49. * @param {options}
  50. * data String / ArrayBuffer 是 需要发送的内容
  51. * success Function 否 接口调用成功的回调函数
  52. * fail Function 否 接口调用失败的回调函数
  53. * complete Function 否 接口调用结束的回调函数(调用成功、失败都会执行)
  54. */
  55. sendSocketMessage: function (options) {
  56. if (socketOpen) {
  57. wx.sendSocketMessage({
  58. data: options.msg,
  59. success: function (res) {
  60. if (options) {
  61. options.success && options.success(res);
  62. }
  63. },
  64. fail: function (res) {
  65. console.log(res);
  66. if (options) {
  67. options.fail && options.fail(res);
  68. }
  69. }
  70. })
  71. } else {
  72. socketMsgQueue.push(options.msg)
  73. }
  74. },
  75. /**
  76. * 关闭 WebSocket 连接。
  77. * @param {options}
  78. * code Number 否 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭)
  79. * reason String 否 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符)
  80. * fail Function 否 接口调用失败的回调函数
  81. * complete Function 否 接口调用结束的回调函数(调用成功、失败都会执行)
  82. */
  83. closeSocket: function (options) {
  84. if (connectSocketTimeOut) {
  85. clearTimeout(connectSocketTimeOut);
  86. connectSocketTimeOut = null;
  87. }
  88. socketClose = true;
  89. var self = this;
  90. self.stopHeartBeat();
  91. wx.closeSocket({
  92. success: function (res) {
  93. console.log('WebSocket 已关闭!');
  94. if (options) {
  95. options.success && options.success(res);
  96. }
  97. },
  98. fail: function (res) {
  99. if (options) {
  100. options.fail && options.fail(res);
  101. }
  102. }
  103. })
  104. },
  105. // 收到消息回调
  106. onSocketMessageCallback: function (msg) {
  107. },
  108. // 开始心跳
  109. startHeartBeat: function () {
  110. console.log('socket开始心跳')
  111. var self = this;
  112. heart = 'heart';
  113. self.heartBeat();
  114. },
  115. // 结束心跳
  116. stopHeartBeat: function () {
  117. console.log('socket结束心跳')
  118. var self = this;
  119. heart = '';
  120. if (heartBeatTimeOut) {
  121. clearTimeout(heartBeatTimeOut);
  122. heartBeatTimeOut = null;
  123. }
  124. if (connectSocketTimeOut) {
  125. clearTimeout(connectSocketTimeOut);
  126. connectSocketTimeOut = null;
  127. }
  128. },
  129. // 心跳
  130. heartBeat: function () {
  131. var self = this;
  132. if (!heart) {
  133. return;
  134. }
  135. self.sendSocketMessage({
  136. msg: JSON.stringify({
  137. form_id: getApp().UserId(),
  138. type: 'resetChatTotal'})})
  139. self.sendSocketMessage({
  140. msg: JSON.stringify({
  141. form_id: getApp().UserId(),
  142. type: 'login'
  143. }),
  144. success: function (res) {
  145. console.log('socket心跳成功');
  146. if (heart) {
  147. heartBeatTimeOut = setTimeout(() => {
  148. self.heartBeat();
  149. }, 120000);
  150. }
  151. },
  152. fail: function (res) {
  153. console.log('socket心跳失败');
  154. if (heartBeatFailCount > 2) {
  155. // 重连
  156. self.connectSocket();
  157. }
  158. if (heart) {
  159. heartBeatTimeOut = setTimeout(() => {
  160. self.heartBeat();
  161. }, 7000);
  162. }
  163. heartBeatFailCount++;
  164. },
  165. });
  166. }
  167. }
  168. // 监听WebSocket连接打开事件。callback 回调函数
  169. wx.onSocketOpen(function (res) {
  170. console.log('WebSocket连接已打开!')
  171. // wx.hideLoading();
  172. // 如果已经调用过关闭function
  173. if (socketClose) {
  174. webSocket.closeSocket();
  175. } else {
  176. socketOpen = true
  177. // webSocket.sendSocketMessage({
  178. // msg: JSON.stringify({
  179. // form_id: getApp().UserId(),
  180. // type: 'login'
  181. // }),
  182. // success: function (e) {
  183. // console.log('socket登录成功');
  184. // }
  185. // })
  186. for (var i = 0; i < socketMsgQueue.length; i++) {
  187. webSocket.sendSocketMessage(socketMsgQueue[i])
  188. }
  189. socketMsgQueue = []
  190. webSocket.startHeartBeat();
  191. }
  192. })
  193. // 监听WebSocket错误。
  194. wx.onSocketError(function (res) {
  195. console.log('WebSocket连接打开失败,请检查!', res)
  196. })
  197. // 监听WebSocket接受到服务器的消息事件。
  198. wx.onSocketMessage(function (res) {
  199. let data = JSON.parse(res.data);
  200. console.log(data);
  201. switch(data.type){
  202. case 'resetChatTotal':
  203. if (data.data.message_exists == true){
  204. wx.showTabBarRedDot({
  205. index: 0,
  206. })
  207. }else{
  208. wx.removeTabBarBadge({
  209. index: 0,
  210. });
  211. // wx.setTabBarBadge({
  212. // index: 0
  213. // })
  214. }
  215. break;
  216. }
  217. console.log('没有回调之前的方法:' + res.data)
  218. webSocket.onSocketMessageCallback(res.data);
  219. })
  220. // 监听WebSocket关闭。
  221. wx.onSocketClose(function (res) {
  222. console.log('WebSocket 已关闭!')
  223. if (!socketClose) {
  224. clearTimeout(connectSocketTimeOut)
  225. connectSocketTimeOut = setTimeout(() => {
  226. webSocket.connectSocket();
  227. }, 3000);
  228. }
  229. })
  230. // 监听WebSocket关闭。
  231. wx.onSocketClose(function (res) {
  232. console.log('WebSocket 已关闭!')
  233. if (!socketClose) {
  234. clearTimeout(connectSocketTimeOut)
  235. connectSocketTimeOut = setTimeout(() => {
  236. webSocket.connectSocket();
  237. }, 3000);
  238. }
  239. })
  240. module.exports = webSocket;