当连接一个url的时候,我们就按照传统的方式写就可以了
initWebSocket: function () {
if ("WebSocket" in window){
let url ='ws://'+ this.baseUrl.split('//')[1] +'/TotalEmergeProgressWebsocket'
console.log(url)
this.websock = new WebSocket(url);
}
else{
alert('该浏览器不支持websocket')
}
this.websock.onopen = this.websocketOnopen;
this.websock.onmessage = this.websocketOnmessage;
this.websock.onerror = this.websocketOnerror;
this.websock.onclose = this.websocketOnclose;
},
websocketOnopen: function () {
console.log("WebSocket连接成功");
// 设置定时器
// 如果状态为正在爬取就设置定时器
//心跳检测重置
// this.heartCheck.reset().start();
},
websocketOnerror: function (e) {
console.log("WebSocket连接发生错误");
this.reconnect();
},
websocketOnmessage: function (e) {
this.loading = true
console.log("-----接收消息-------",e.data);
var data = eval("(" + e.data + ")"); //解析对象
console.log(this.percentage)
this.percentage = (data.emergedDataNum/data.totalDataNum).toFixed(1)*100;
// 如果进度到了100%
if(data.totalDataNum === (data.emergedDataNum+data.errorTableNum)){
//关闭websocket连接,并且请求失败的数据
this.websock.close();
this.loading = false
this.getFailDB()
}
},
websocketOnclose: function (e) {
console.log("connection closed (" + e.code + ")");
this.reconnect();
},
websocketSend(text) { // 数据发送
try {
this.websock.send(text);
} catch (err) {
console.log("send failed (" + err.code + ")");
}
},
reconnect() {
var that = this;
if(that.lockReconnect) return;
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
setTimeout(function () {
console.info("尝试重连...");
that.initWebSocket();
that.lockReconnect = false;
}, 20000);
},
我们把它定义成公共类。
import { ElMessage } from 'element-plus'
let wsUrl = `ws://localhost:8082/TableEmergeProgressWebsocket`
let lockReconnect = true;
let callback = null;
let socket = null;
function getConnect(callback,pageUrl){
if ("WebSocket" in window){
const requestWsUrl = wsUrl + pageUrl;
console.log(requestWsUrl)
socket = new WebSocket(requestWsUrl);
}
else{
alert('该浏览器不支持websocket')
}
socket.onmessage = function (e) {
callback(e,socket);
}
socket.onopen = function () {
console.log("WebSocket子表连接成功");
}
socket.onerror = function () {
ElMessage.error('ws连接发生错误');
reconnect(pageUrl);
}
socket.onclose = function (e) {
console.log("connection closed (" + e.code + ")");
}
}
function reconnect(pageUrl){
if(lockReconnect) return;
lockReconnect = true;
setTimeout(function () {
console.info("尝试重连...");
this.getConnect(callback,pageUrl);
lockReconnect = false;
}, 20000);
}
export default getConnect
在具体的页面组件重写回调函数