前端 websocket使用
export default class SocketService {
constructor(url, againConnect = true) {
this.url = url;
this.againConnect = againConnect;
}
instance = null;
ws = null;
url = "";
againConnect;
connected = false;
sendRetryCount = 0;
connectRetryCount = 0;
static get Instance() {
if (!this.instance) {
const url = "ws://192.168.0.11:8888";
this.instance = new SocketService(url, true);
}
return this.instance;
}
connect() {
if (!window.WebSocket) {
return console.log("您的浏览器不支持WebSocket");
}
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
this.connected = true;
this.connectRetryCount = 0;
};
this.ws.onclose = () => {
for (let key in this.subscribeList) {
const obj = {
code: 1,
msg: "服务器异常,请稍后重试",
data: null,
};
this.subscribeList[key].forEach(item => item.call(this, obj));
}
this.connected = false;
this.connectRetryCount++;
if (this.againConnect) {
setTimeout(() => {
this.connect();
}, 500 * this.connectRetryCount);
} else {
sessionStorage.clear();
localStorage.clear();
}
};
this.ws.onerror = () => {
for (let key in this.subscribeList) {
const obj = {
code: 1,
msg: "服务器异常,请稍后重试",
data: null,
};
this.subscribeList[key].forEach(item => item.call(this, obj));
}
this.connected = false;
this.connectRetryCount++;
if (this.againConnect) {
setTimeout(() => {
this.connect();
}, 500 * this.connectRetryCount);
}
};
this.ws.onmessage = e => {
if (e.data) {
let resData = JSON.parse(e.data);
const requestId = resData.uuid;
resData.data = resData.data ? JSON.parse(resData.data) : {};
if (this.subscribeList[requestId]) {
this.subscribeList[requestId].forEach(item => item.call(this, resData));
}
} else {
console.log("服务器异常");
for (let key in this.subscribeList) {
const obj = {
code: 1,
msg: "服务器异常,请稍后重试",
data: null,
};
this.subscribeList[key].forEach(item => item.call(this, obj));
}
}
};
}
unSubscribe() {
this.idList.forEach(item => {
delete this.subscribeList[item];
});
this.idList = [];
}
subscribeList = {};
idList = [];
send(data, callback) {
if (!this.ws) {
this.connect();
this.send(data, callback);
} else {
if (this.connected) {
this.sendRetryCount = 0;
this.ws.send(JSON.stringify(data));
this.idList.push(data.uuid);
if (!this.subscribeList[data.uuid]) {
this.subscribeList[data.uuid] = [callback];
} else {
this.subscribeList[data.uuid].push(callback);
}
} else {
this.sendRetryCount++;
setTimeout(() => {
this.send(data, callback);
}, this.sendRetryCount * 500);
}
}
}
}
import SocketService from "../js/socket.js";
mounted() {
this.ws = SocketService.Instance;
this.sendRequest("getuser", {}, callback);
},
destroyed() {
this.ws.unSubscribe();
},
methods:{
sendRequest(api, params, callback) {
const uuid = "123e4567-e89b-12d3-a456-426655440000";
const data = {
route: api,
uuid: uuid,
params: params,
};
this.ws.send(data, callback);
},
callback(res) {
if (res.code == 0) {
console.log(res);
} else {
Message.error(res.msg);
}
},
}