使用ws
import QueryWebSocket from "websocket";
createWebSocket() {
this.webSocket = new QueryWebSocket({
url: `wss://websocket/ws/notice/`,
createSuccess: () => { },
queryData: (res) => {
console.log(res);
},
})
},
webSocket.js 封装文件
const QueryWebSocket = function (obj1) {
let obj = obj1 || {};
const defaultObj = {
url: "",
lockReconnect: false,
ws: "",
tt: "",
timeout: 30000,
timeoutObj: null,
};
this.config = Object.assign(defaultObj, obj);
if ("WebSocket" in window) {
console.log("支持WebSocket");
const that = this;
setTimeout(function () {
that.createWebSocket();
}, 1000);
} else {
alert("该浏览器不支持WebSocket");
}
};
QueryWebSocket.prototype = {
QueryWebSocket: QueryWebSocket,
reset: function () {
clearTimeout(this.config.timeoutObj);
this.config.ws.onclose();
},
start: function () {
const that = this;
this.config.timeoutObj = setInterval(function () {
let message = "I";
that.config.ws.send(message);
}, 15000);
},
createWebSocket: function () {
try {
this.config.ws = new WebSocket(this.config.url);
this.webSocketInit();
} catch (e) {
console.log("catch",e.message);
this.webSocketReconnect(this.config.url);
}
},
sendContent: function (data) {
this.config.ws.send(JSON.stringify(data));
},
webSocketInit: function () {
const that = this;
that.config.ws.onclose = function () {
console.log("连接已关闭...",new Date());
clearTimeout(that.config.timeoutObj);
that.webSocketReconnect(that.config.url)
};
that.config.ws.onerror = function () {
console.log("连接错误...",new Date());
that.webSocketReconnect(that.config.url);
};
that.config.ws.onopen = function () {
console.log("链接成功",new Date());
that.config.lockReconnect = false;
that.config.ws.send("I");
that.start();
};
that.config.ws.onmessage = function (evt) {
if (evt.data !== "O") {
if (JSON.parse(evt.data).content !== "PONG") {
that.config.queryData(JSON.parse(evt.data));
}
}
};
},
webSocketReconnect: function (url) {
const that = this;
console.log("socket 连接断开,正在尝试重新建立连接");
if (that.config.lockReconnect) {
return;
}
that.config.lockReconnect = true;
that.config.tt && clearTimeout(that.config.tt);
that.config.tt = setTimeout(function () {
that.createWebSocket(url);
}, 4000);
},
};
export default QueryWebSocket;