WebSocket 工具类
const WS_URL = 'https://demo.com:80';
const initMessage = 'myMessage';
let ws = window._ws_;
const WebSocketServe = {
id: null,
create(_id) {
if('WebSocket' in window) {
if(ws) {
if(ws.readyState === 1) ws.send(initMessage)
if(ws.readyState === 0) setTimeout(() => { ws.send(initMessage) }, 1000)
}else {
window._ws_ = new WebSocket(WS_URL+'?id'= 123)
}
ws.onopen = function() {
WebSocketServe.id = _id;
ws.send(initMessage)
}
ws.onmessage = function (evt) {
console.log(evt.data)
};
ws.onclose = function() {
setTimeout(() =>{
WebSocketServe.id && WebSocketServe.create(this.id)
}, 1000)
}
ws.error = function() {
console.log('socket 连接错误')
}
} else {
alert("您的浏览器不支持 WebSocket!");
}
},
destroyed() {
if(ws && ws.readyState === 1) ws.close();
this.id = null;
window._ws_ = null;
}
}
export default WebSocketServe;