let websock = null
let lockReconnect = false
let timeout = 1000
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 = () => {
const wsuri = 'wss://'
websock = new WebSocket(wsuri);
websock.onopen = this.websocketonopen;
websock.onerror = this.websocketonerror;
websock.onmessage = this.websocketonmessage;
}
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;