data(){
return{
ws: null,
isConnected: false,
heartbeatInterval: null, // 保存心跳定时器的ID
heartbeatTimeout: 5000, // 心跳间隔时间
}
}
methods:{
initConnect(){
this.ws = new WebSocket(`ws://192.10`);//websocket连接地址
this.ws.onopen = () => {
console.log('WebSocket连接已建立');
this.isConnected = true;
// 建立心跳定时器
this.heartbeatInterval = setInterval(() => {
if (this.ws.readyState === 1) {
this.ws.send(JSON.stringify({ type: 'heartbeat' }));
console.log("心跳开启")
}
}, this.heartbeatTimeout);
};
this.ws.onmessage = (event) => {
const dataMessage = JSON.parse(event.data);
console.log(dataMessage, "接收到的信息");
};
this.ws.onerror = () => {
console.error('WebSocket连接发生错误');
};
this.ws.onclose = () => {
console.log('WebSocket连接已关闭');
this.ws.send('close');
this.isConnected = false;
// 清除心跳定时器
clearInterval(this.heartbeatInterval);
};
}
mounted:{
this.initConnect()
}
如有疑问请私信