ws.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import {
  2. API_URL,
  3. API_ROOT,
  4. UNIACID
  5. } from '@/common/request/request';
  6. import store from "@/common/store";
  7. //是否已经连接上ws
  8. let isOpenSocket = false
  9. //心跳间隔,单位毫秒
  10. let heartBeatDelay = 10000
  11. let heartBeatInterval = null
  12. //心跳时发送的消息文本
  13. let heartBeatText = "PING"
  14. //最大重连次数
  15. let reconnectTimes = 10
  16. let reconnectInterval = null
  17. //重连间隔,单位毫秒
  18. let reconnectDelay = 5000
  19. var url = API_ROOT;
  20. var domain = url.split("/"); //以“/”进行分割
  21. if( domain[2] ) {
  22. domain = domain[2];
  23. } else {
  24. domain = ""; //如果url不正确就取空
  25. }
  26. // console.log("wss://"+domain+":8288");
  27. //let wsUrl = "wss://faraway.wike.cc/wss" //ws请求 或者 wss
  28. let wsUrl = [{url:'wss://away.wike.cc/wss'},{url:'wss://faraway.wike.cc/wss'}];
  29. let socketTask = null
  30. //这个参数是防止重连失败之后onClose方法会重复执行reconnect方法,导致重连定时器出问题
  31. //连接并打开之后可重连,且只执行重连方法一次
  32. let canReconnect = false
  33. //封装的对象,最后以模块化向外暴露,
  34. //init方法 初始化socketTask对象
  35. //completeClose方法 完全将socketTask关闭(不重连)
  36. //其他关于socketTask的方法与uniapp的socketTask api一致
  37. let ws = {
  38. socketTask: null,
  39. init,
  40. completeClose,
  41. send,
  42. socketStatus
  43. }
  44. function init(s) {
  45. let u = wsUrl[uni.$u.random(0, 1)].url;
  46. // if(store.getters.appInfo && store.getters.appInfo.connect_lines){
  47. // if(store.getters.appInfo.connect_lines == 2){
  48. // wsUrl = "wss://faraway.wike.cc/wss"
  49. // }
  50. // }
  51. socketTask = uni.connectSocket({
  52. url: u,
  53. complete: (res)=> {console.log("WebSocket连接成功",res,u)}
  54. })
  55. socketTask.onOpen((res) => {
  56. console.log("WebSocket连接已打开",res)
  57. clearInterval(heartBeatInterval)
  58. clearInterval(reconnectInterval)
  59. isOpenSocket = true
  60. canReconnect = true
  61. //开启心跳机制 向websocket发送数据,json格式,参数:sceneId
  62. // heartBeat()
  63. })
  64. socketTask.onMessage((res) => {
  65. // 每次返回的数据不一样,需要加入判断
  66. // console.log('收到服务器内容',JSON.parse(res.data))
  67. // let result = JSON.parse(res.data)
  68. //      //这边可以根据推送的数据, 做相应的 do somethings, 根据自己需求, 下面只是例子..
  69. // // token存在,说明,小程序用户点击了授权(比如推送的数据有token,那就做什么事xxxx
  70. // send('{"state":"bind","fromid":"' + store.getters.userInfo.id + '"}')
  71. // if(result.state == 'new_content'){
  72. // uni.vibrateLong({
  73. // success: function () {
  74. // // console.log('success');
  75. // }
  76. // });
  77. // uni.showTabBarRedDot({
  78. // index:2
  79. // })
  80. // }
  81. // if(result.token){
  82. // uni.setStorageSync('token', result.token)
  83. // uni.setStorageSync('userInfo', JSON.stringify(result.userInfo))
  84. // }
  85. // client_id存在,说明连websocket接成功
  86. // if(result.msg=="连接成功"){
  87. // uni.setStorageSync('client_id', result.data.client_id);
  88. // }
  89. // JSON.parse(res.data).msg=="已归还导览机", 已归还导览机,清空用户缓存
  90. // if(result.msg=="已归还导览机"){
  91. // uni.clearStorageSync();
  92. // uni.navigateBack({
  93. // delta: 100
  94. // })
  95. // }
  96. })
  97. socketTask.onClose(() => {
  98. // console.log(isOpenSocket);
  99. if(isOpenSocket){
  100. console.log("ws与服务器断开")
  101. }else{
  102. console.log("连接失败")
  103. }
  104. isOpenSocket = false
  105. if(canReconnect){
  106. reconnect()
  107. canReconnect = false
  108. }
  109. })
  110. ws.socketTask = socketTask
  111. }
  112. function socketStatus() {
  113. return isOpenSocket;
  114. }
  115. function heartBeat() {
  116. heartBeatInterval = setInterval(() => {
  117. // console.log(heartBeatText)
  118. uni.getSystemInfo({
  119. success: function (res) {
  120. //console.log('设备id----',res.deviceId);//设备id
  121. uni.setStorageSync('deviceId', res.deviceId)
  122. let obj = {
  123. sceneId:res.deviceId
  124. }
  125. send(JSON.stringify(obj));
  126. }
  127. });
  128. }, heartBeatDelay)
  129. }
  130. // 发送消息
  131. function send(value) {
  132. ws.socketTask.send({
  133. data: value,
  134. async success(res) {
  135. // console.log("消息发送成功",res,value)
  136. }
  137. });
  138. }
  139. function reconnect() {
  140. //停止发送心跳
  141. clearInterval(heartBeatInterval)
  142. //如果不是人为关闭的话,进行重连
  143. if (!isOpenSocket) {
  144. let count = 0;
  145. // reconnectInterval = setInterval(() => {
  146. console.log("正在尝试重连")
  147. init();
  148. count++
  149. //重连一定次数后就不再重连
  150. if(count >= reconnectTimes){
  151. // clearInterval(reconnectInterval)
  152. console.log("网络异常或服务器错误")
  153. }
  154. // }, reconnectDelay)
  155. }
  156. }
  157. function completeClose(){
  158. //先将心跳与重连的定时器清除
  159. console.log('停止连接');
  160. clearInterval(heartBeatInterval)
  161. clearInterval(reconnectInterval)
  162. canReconnect = false
  163. ws.socketTask.close()
  164. }
  165. module.exports = ws