封装 webSocket.js
class webSocket {
constructor(options) {
this.ws = null;
this.url = options.url;
this.status = null;
this.isHeart = options.isHeart;
this._timeout = 30000;
this.callback = options.received;
this.pingInterval = null;
this.lockReconnect = false;
this.isReconnec = options.isReconnec;
this.data = options.data || '';
this.connect();
}
connect() {
if (this.lockReconnect) {
return;
}
this.lockReconnect = true;
this.createWebSocket();
this.lockReconnect = false;
}
createWebSocket() {
if ('WebSocket' in window) {
this.ws = new WebSocket(this.url);
} else if ('MozWebSocket' in window) {
this.ws = new MozWebSocket(this.url);
} else {
console.log('您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器,请勿使用IE10以下浏览器')
}
this.initEvent();
}
initEvent() {
this.ws.onopen = (e) => {
this.status = 'open';
if(this.isHeart) {
this._heartCheck()
}
// 给后台发送数据
if(this.data) {
return this.ws.send(JSON.stringify(this.data))
}
}
this.ws.onmessage = (e) => {
if(typeof this.callback === 'function'){
return this.callback(e.data)
}else{
console.log('no function')
}
}
this.ws.onclose = (e) => {
this._close(e)
}
this.onerror = (e) => {
this._close(e)
}
}
_resetHeart() {
clearInterval(this.pingInterval)
return this
}
_heartCheck() {
this.pingInterval = setInterval(() => {
if(this.ws.readyState === 1) {
this.ws.send(JSON.stringify({type: 'ping'}))
}
}, this._timeout)
}
_close(e) {
this._resetHeart()
if(this.status !== 'close') {
if(this.isReconnec){
this.connect()
}
}else{
console.log(e)
}
}
close() {
this.status = 'close'
this._resetHeart()
return this.ws.close();
}
send(data) {
return this.ws.send(JSON.stringify(data))
}
}
html 代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
123
</body>
<script src="/static/js/websocket.js"></script>
<script>
const ws = new webSocket({
url: 'ws://127.0.0.1:9543',
isHeart: true,
isReconnec: true,
data: 13475869
});
// ws.send(456789)
// 关闭
window.onbeforeunload = function () {
ws.close();
}
</script>
</html>