websocket_sdk.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import packetCode from './PacketCodeC.js'
  2. import store from './store/index.js'
  3. export default class Websocket {
  4. constructor({
  5. heartCheck,
  6. isReconnection
  7. }) {
  8. // 是否连接
  9. this._isLogin = false;
  10. // 当前网络状态
  11. this._netWork = true;
  12. // 是否人为退出
  13. this._isClosed = false;
  14. // 心跳检测频率
  15. this._timeout = 3000;
  16. this._timeoutObj = null;
  17. // 当前重连次数
  18. this._connectNum = 0;
  19. // 心跳检测和断线重连开关,true为启用,false为关闭
  20. this._heartCheck = heartCheck;
  21. this._isReconnection = isReconnection;
  22. // this._onSocketOpened();
  23. }
  24. // 心跳重置
  25. _reset() {
  26. clearTimeout(this._timeoutObj);
  27. return this;
  28. }
  29. // 心跳开始
  30. _start() {
  31. let _this = this;
  32. this._timeoutObj = setInterval(() => {
  33. //发送心跳
  34. _this.sendHeartbeatData();
  35. }, this._timeout);
  36. }
  37. // 监听websocket连接关闭
  38. onSocketClosed(options) {
  39. uni.onSocketError(err => {
  40. console.log('当前websocket连接已关闭,错误信息为:' + JSON.stringify(err));
  41. // 停止心跳连接
  42. if (this._heartCheck) {
  43. this._reset();
  44. }
  45. // 关闭已登录开关
  46. this._isLogin = false;
  47. // 检测是否是用户自己退出小程序
  48. console.log('------------------开启重连--------------------------------')
  49. if (!this._isClosed) {
  50. // 进行重连
  51. if (this._isReconnection) {
  52. this._reConnect(options)
  53. }
  54. }
  55. })
  56. uni.onSocketClose(err => {
  57. })
  58. }
  59. // 检测网络变化
  60. onNetworkChange(options) {
  61. uni.onNetworkStatusChange(res => {
  62. console.log('当前网络状态:' + res.isConnected);
  63. if (!this._netWork) {
  64. this._isLogin = false;
  65. // 进行重连
  66. if (this._isReconnection) {
  67. this._reConnect(options)
  68. }
  69. }
  70. })
  71. }
  72. _onSocketOpened() {
  73. uni.onSocketOpen(res => {
  74. console.log('【websocket】已打开');
  75. // 打开已登录开关
  76. this._isLogin = true;
  77. // 发送心跳
  78. if (this._heartCheck) {
  79. this._reset()._start();
  80. }
  81. // 发送登录信息
  82. this.sendLoginData();
  83. // 打开网络开关
  84. this._netWork = true;
  85. })
  86. }
  87. // 接收服务器返回的消息
  88. onReceivedMsg(callBack) {
  89. uni.onSocketMessage(event => {
  90. if (typeof callBack == "function") {
  91. callBack(event)
  92. } else {
  93. console.log('参数的类型必须为函数')
  94. }
  95. })
  96. }
  97. // 建立websocket连接
  98. initWebSocket(options) {
  99. let _this = this;
  100. if (this._isLogin) {
  101. console.log("您已经登录了");
  102. } else {
  103. // 检查网络
  104. uni.getNetworkType({
  105. success(result) {
  106. if (result.networkType != 'none') {
  107. // 开始建立连接
  108. console.log('建立websocket连接' + options.url);
  109. uni.connectSocket({
  110. url: options.url,
  111. success(res) {
  112. if (typeof options.success == "function") {
  113. options.success(res)
  114. _this._onSocketOpened();
  115. } else {
  116. console.log('参数的类型必须为函数')
  117. }
  118. },
  119. fail(err) {
  120. if (typeof options.fail == "function") {
  121. options.fail(err)
  122. } else {
  123. console.log('参数的类型必须为函数')
  124. }
  125. }
  126. })
  127. } else {
  128. console.log('网络已断开');
  129. _this._netWork = false;
  130. // 网络断开后显示model
  131. uni.showModal({
  132. title: '网络错误',
  133. content: '请重新打开网络',
  134. showCancel: false,
  135. success: function(res) {
  136. if (res.confirm) {
  137. console.log('用户点击确定')
  138. }
  139. }
  140. })
  141. }
  142. }
  143. })
  144. }
  145. }
  146. // 发送websocket消息
  147. sendWebSocketMsg(options) {
  148. this.sendBinary(1,options);
  149. }
  150. //发送心跳连接
  151. sendHeartbeatData() {
  152. let packet = {
  153. version: 1,
  154. command: 17,
  155. token: store.state.userData.token
  156. }
  157. this.sendBinary(99, {
  158. data: packet,
  159. success(res) {
  160. // console.log('【websocket】心跳连接成功');
  161. },
  162. fail(err) {
  163. console.log('【websocket】心跳连接失败');
  164. console.log(err)
  165. //开启重连
  166. }
  167. });
  168. }
  169. //发送第一次连接数据
  170. sendLoginData() {
  171. this.sendBinary(99, {
  172. data: {},
  173. success(res) {
  174. console.log('【websocket】第一次连接成功')
  175. },
  176. fail(err) {
  177. console.log('【websocket】第一次连接失败')
  178. console.log(err)
  179. }
  180. });
  181. // this.sendBinary(99, {});
  182. // socket.sendSocketMessage({
  183. // // 这里是第一次建立连接所发送的信息,应由前后端商量后决定
  184. // data: JSON.stringify({
  185. // "key": 'value'
  186. // })
  187. // })
  188. }
  189. // 重连方法,会根据时间频率越来越慢
  190. _reConnect(options) {
  191. let timer, _this = this;
  192. if (this._connectNum < 20) {
  193. timer = setTimeout(() => {
  194. this.initWebSocket(options)
  195. }, 500)
  196. this._connectNum += 1;
  197. } else if (this._connectNum < 50) {
  198. timer = setTimeout(() => {
  199. this.initWebSocket(options)
  200. }, 1000)
  201. this._connectNum += 1;
  202. } else {
  203. timer = setTimeout(() => {
  204. this.initWebSocket(options)
  205. }, 3000)
  206. this._connectNum += 1;
  207. }
  208. }
  209. // 关闭websocket连接
  210. closeWebSocket() {
  211. uni.closeSocket();
  212. this._isClosed = true;
  213. }
  214. //发送二进制
  215. sendBinary(commendType, options) {
  216. uni.sendSocketMessage({
  217. data: packetCode.encode(options.data),
  218. success(res) {
  219. if (typeof options.success == "function") {
  220. options.success(res)
  221. } else {
  222. console.log('参数的类型必须为函数')
  223. }
  224. },
  225. fail(err) {
  226. if (typeof options.fail == "function") {
  227. options.fail(err)
  228. } else {
  229. console.log('参数的类型必须为函数')
  230. }
  231. }
  232. });
  233. }
  234. }