react 实现websoketc长连接

2,165 阅读1分钟
let websock = null//建立的连接
let lockReconnect = false//是否真正建立连接
let timeout = 1000//30秒一次心跳
let timeoutObj = null//心跳心跳倒计时
let serverTimeoutObj = null//心跳倒计时
let timeoutnum = null//断开 重连倒计时

class Websoket extends React.Component {
  constructor (props) {
    super(props);
  }
  componentWillUnmount () {
    //页面销毁时关闭长连接
    this.websocketclose();
  }
  componentDidMount(){
    this.initWebSocket();
  }

  initWebSocket = () => {//建立连接
    //初始化weosocket
    const wsuri =  'wss://'
    //建立连接
    websock = new WebSocket(wsuri);
    //连接成功
    websock.onopen = this.websocketonopen;
    //连接错误
    websock.onerror = this.websocketonerror;
    //接收信息
    websock.onmessage = this.websocketonmessage;
    //连接关闭
    // websock.onclose = this.websocketclose;
}

reconnect = () =>{//重新连接
    let that = this;
    if(lockReconnect) {
        return;
    };
    lockReconnect = true;
    //没连接上会一直重连,设置延迟避免请求过多
    timeoutnum && clearTimeout(timeoutnum);
    timeoutnum = setTimeout(function () {
        //新连接
        that.initWebSocket();
        lockReconnect = false;
    },5000);
}

reset = () =>{//重置心跳
    var that = this;
    //清除时间
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    //重启心跳
    that.start();
}

start = () => {//开启心跳
    var self = this;
    timeoutObj && clearTimeout(timeoutObj);
    serverTimeoutObj && clearTimeout(serverTimeoutObj);
    timeoutObj = setTimeout(function(){
        //这里发送一个心跳,后端收到后,返回一个心跳消息,
        if (websock.readyState == 1) {//如果连接正常
            let msg = self.props.uid+'|'+self.props.userId
            websock.send(msg);
        }else{//否则重连
            self.reconnect();
        }
       serverTimeoutObj = setTimeout(function() {
            //超时关闭
           websock.close();
        },timeoutObj);

    }, timeout)
}

websocketonopen = () => {//连接成功事件
    console.log('链接成功')
    //开启心跳
    this.start();
}

websocketonerror = (e) =>{//连接失败事件
    //错误
    console.log(e,"WebSocket连接发生错误");
    //重连
    this.reconnect();
}
websocketclose = (e) =>{//连接关闭事件
    //关闭
    console.log('连接关闭');
    //重连
    this.reconnect();
}
websocketonmessage = (event) => {//接收服务器推送的信息
    console.log(event)
}
render = () => {
    return <></>
}
}
export default Websoket;