wsRequest.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. class wsRequest {
  2. constructor(time) {
  3. this.status = null; // websocket是否关闭
  4. this.lockReconnect = false //避免重复连接
  5. // this.url = url
  6. //心跳检测
  7. this.timeout = time //多少秒执行检测
  8. this.timeoutObj = null //检测服务器端是否还活着
  9. this.reconnectTimeOutObj = null //重连之后多久再次重连
  10. try {
  11. return this.initRequest()
  12. } catch (e) {
  13. this.reconnect();
  14. }
  15. }
  16. initRequest() {
  17. this.socketTask = uni.connectSocket({
  18. url: 'wss://' + uni.getStorageSync("wsServerUrl") + '/websocket/message/' + uni.getStorageSync(
  19. 'setUserName'), //接口地址。
  20. success: () => {
  21. // 返回实例
  22. return this.socketTask
  23. }
  24. })
  25. this.socketTask.onOpen(res => {
  26. // 清除重连定时器
  27. clearTimeout(this.reconnectTimeOutObj)
  28. // 开启检测
  29. this.start()
  30. })
  31. // 如果希望websocket连接一直保持,在close或者error上绑定重新连接方法。
  32. this.socketTask.onClose((res) => {
  33. console.log(res, '连接关闭');
  34. this.reconnect();
  35. })
  36. this.socketTask.onError((res) => {
  37. console.log(res, '连接错误');
  38. this.reconnect();
  39. })
  40. this.socketTask.onMessage(res => {
  41. //接受任何消息都说明当前连接是正常的
  42. this.reset();
  43. if (res.data === 'all_Read') {
  44. uni.setStorageSync('msgData', null)
  45. } else if (res.data != 'ping') {
  46. uni.setStorageSync('msgData', res.data)
  47. } else {
  48. uni.setStorageSync('msgData', null)
  49. }
  50. })
  51. }
  52. send(value) {
  53. return new Promise((resovle, reject) => {
  54. this.socketTask.send({
  55. data: value,
  56. success: () => {
  57. resovle('发送成功')
  58. }
  59. })
  60. })
  61. }
  62. // reset和start方法主要用来控制心跳的定时。
  63. reset() {
  64. // 清除定时器重新发送一个心跳信息
  65. clearTimeout(this.timeoutObj);
  66. this.start();
  67. }
  68. start() {
  69. this.timeoutObj = setTimeout(() => {
  70. //这里发送一个心跳,后端收到后,返回一个心跳消息,
  71. //onmessage拿到返回的心跳就说明连接正常
  72. this.socketTask.send({
  73. data: "ping"
  74. });
  75. }, this.timeout)
  76. }
  77. // 重连
  78. reconnect() {
  79. // 防止多个方法调用,多处重连
  80. if (this.lockReconnect) {
  81. return;
  82. };
  83. this.lockReconnect = true;
  84. console.log('准备重连');
  85. //没连接上会一直重连,设置延迟避免请求过多
  86. this.reconnectTimeOutObj = setTimeout(() => {
  87. // 重新连接
  88. this.initRequest()
  89. this.lockReconnect = false;
  90. }, 4000);
  91. }
  92. // 手动关闭
  93. close() {
  94. this.socketTask.close()
  95. }
  96. }
  97. module.exports = wsRequest