websocket andorid 断网重连报onError 跟ios逻辑不一样
发布于 6 年前 作者 fangfu 7729 次浏览 来自 问答

Android 断网重连会一直onError  不回调 onClose , 重连5次以上就报fail max connected . 一样的操作ios会回调onError 然后回调onClose ,连接网络ios长链正常,而Android报错。class Socket {

 static getInstance() {
  if (!this.instance) {
   this.instance = new Socket();
  }
  return this.instance;
 }
 constructor() {
  this.instance = null;
  this.socketTask = null
  this.timer = null
  this.proto = new Proto()
  // this.socketOpen = false //im长连接的状态
  this.hb = null
  this.reConnectTime = null
  this.allowReconnect = false

 }

createSocket() {

  if (this.socketTask) {
   console.log(‘有socketTask’)
   if (this.socketTask.readyState === 1) {
    this.close().then(res => {

    }).catch(err => {
     // console.log(’---- 有socketTask ----’)
     console.error(err)
     this.socketTaskHandler()
    })
   }else{
    this.socketTaskHandler()
   }
   
  } else {
   this.socketTaskHandler()
  }
 }

 socketTaskHandler() {
  this.socketTask = uni.connectSocket({
   url: G.im_url() + “websocket”, //this.serverUrl
   setTimeout: 8000,
   success: () => {
    // console.log(“socketTask: sucess!”)
   }
  });
  // this.socketTask.open();
  this.socketTask.onOpen(function(res) {
   // console.log(“socketTask: onOpen!”, res)
   clearInterval(this.reConnectTime)
   this.allowReconnect = false
   let socketOpen = this.socketTask.readyState === 1
   this.login()
   this.heartbeat()
   this.callback(Object.assign(res, {
    socketOpen: socketOpen
   }))
   uni.setStorageSync(“socketOpen”, socketOpen)
  }.bind(this));

  this.socketTask.onError(function(res) {
   console.log(“error:” + JSON.stringify(res))
   this.callback(Object.assign(res, {
    socketOpen: false
   }))
   uni.setStorageSync(“socketOpen”, false)
  }.bind(this));
  this.socketTask.onClose(function() {
   this.reConnectSocket(“onClose”)
   console.log("---------onClose----------")
  }.bind(this));
  this.socketTask.onMessage(function(res) {
   this.onMessage(res.data)
  }.bind(this));
 }

1 回复

麻烦提供出现问题的具体机型、微信版本号、系统版本号,以及能复现问题的代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)

回到顶部