webSoket2封装
const wsReadState = {
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3
};
const defaultOptions = {
hearbeatInterval: 1000,
reconnectCountLimit: 5,
reconnectInterval: 5000
};
class WebSocket2 {
constructor(options) {
this.WS = null;
this.wsUrl = options.wsUrl || "";
this.hearbeatTimer = null;
this.hearbeatInterval = options.hearbeatInterval || defaultOptions.hearbeatInterval;
this.reconnectCountLimit = options.reconnectCountLimit || defaultOptions.reconnectCountLimit;
this.reconnectedCount = 0;
this.reconnectTimer = null;
this.reconnectInterval = options.reconnectInterval || defaultOptions.reconnectInterval;
this.isCloseed = false;
}
init() {
if (!("WebSocket" in window)) {
console.log("当前浏览器不支持WebSocket");
return;
}
if (this.WS) return this.WS;
this.WS = new WebSocket(this.wsUrl);
this.WS.onopen = () => {
console.log("connection successfully.");
this.heartbeat();
};
this.WS.onclose = (e) => {
console.log(`connection closed (code: ${e.code})`);
if (!this.isCloseed) {
this.close();
this.reconnect();
}
};
this.WS.onmessage = (e) => {
this.onMessage(e);
};
this.WS.onerror = () => {
console.log("WebSocket连接发生错误");
this.close();
this.reconnect();
};
}
heartbeat() {
console.log("ping");
if (this.hearbeatTimer) {
clearInterval(this.hearbeatTimer);
}
this.hearbeatTimer = setInterval(() => {
const data = {
kind: 0
};
if (this.WS.readyState === wsReadState.OPEN) {
this.WS.send(JSON.stringify(data));
}
}, this.hearbeatInterval);
}
onMessage(res) {
let dataJSON = JSON.parse(res?.data);
console.log("收到内容:", dataJSON?.data);
}
close(isCloseed) {
console.log("断开连接");
clearInterval(this.hearbeatTimer);
this.isCloseed = isCloseed;
this.WS?.close();
this.WS = null;
}
reconnect() {
console.log("reconnecting...");
this.reconnectTimer = setTimeout(() => {
if (this.reconnectedCount > this.reconnectCountLimit) {
clearTimeout(this.reconnectTimer);
return;
}
this.init();
this.reconnectedCount++;
}, this.reconnectInterval);
}
}
export default WebSocket2;
使用
componentDidMount() {
const ws = new WebSoket2({ wsUrl });
ws.init();
this.setState({ ws });
}
componentWillUnmount() {
const { ws } = this.state;
ws.close(true);
}