React使用webscket

231 阅读1分钟
import React from 'react';

let websock = null//建立的连接
let lockReconnect = false//是否真正建立连接
let timeout = 1000//30秒一次心跳
let timeoutObj = null//心跳心跳倒计时
let serverTimeoutObj = null//心跳倒计时
let timeoutnum = null//断开 重连倒计时
let outdated = false // 判断是否过期
class Websoket extends React.Component {
  constructor (props) {
    super(props);
  }
  componentWillUnmount () {
    //页面销毁时关闭长连接
    this.websocketclose();
  }

  componentWillReceiveProps(nextProps) {
      console.log(nextProps,'nextPropsnextProps',this.props)
      if(nextProps.outdated == false || nextProps.success == false){
        outdated = false
        this.initWebSocket();
      }
  }
  componentDidMount(){
    //   alert(this.props.outdated)
    outdated = this.props.outdated
    // this.initWebSocket();
  }

  initWebSocket = () => {//建立连接
    try {
        if(!this.props.userId && !this.props.uid ){
            console.log('无工号')
            return
        }

        //初始化weosocket
        const wsuri =  global.websocketUrl+this.props.uid
        //建立连接
        websock = new WebSocket(wsuri);
        //连接成功
        websock.onopen = this.websocketonopen;
        //连接错误
        websock.onerror = this.websocketonerror;
        //接收信息
        websock.onmessage = this.websocketonmessage;
        //连接关闭
        // websock.onclose = this.websocketclose;
        // websock.onclose = function (e) {
        //     console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
        //     console.log(e)
        // }
    } catch (e) {
        console.log("报错", e);
    }

}

reconnect = () =>{//重新连接
    if(outdated == true){
        return false
    }
    var 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(){
        //这里发送一个心跳,后端收到后,返回一个心跳消息,
        console.log(websock.readyState,'websock.readyState')
        if (websock.readyState == 1) {//如果连接正常
            let msg = self.props.uid+'|'+self.props.userId
            console.log(msg)
            websock.send(msg);
        }else{//否则重连
            self.reconnect();
        }
       serverTimeoutObj = setTimeout(function() {
            //超时关闭
           websock.close();
        },5000);

    }, timeout)
}

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

websocketonerror = (e) =>{//连接失败事件
    //错误
    console.log(e,"WebSocket连接发生错误");
    //重连
    this.reconnect();
}
websocketclose = (e) =>{//连接关闭事件
    //关闭
    console.log('连接关闭');
    //重连
    this.reconnect();
}
websocketonmessage = (event) => {//接收服务器推送的信息
    this.props.sendStatus(event.data)
    if(event.data == 'outdated'){
        outdated = true
        websock.close();
    }else if( event.data == 'success'){
        let msg = this.props.uid+'|'+this.props.userId+'|'+'success'
        websock.send(msg);
        outdated = true
        websock.close();
    }else {
        outdated = false
        this.reset();
    }
}

render = () => {
    return <></>
}

}
export default Websoket;