// Vue3 WebSocket 封装示例
import { ref, onMounted, onUnmounted } from 'vue';
class WebSocketService {
constructor(url) {
this.url = url;
this.socket = null;
this.isAlive = false;
this.reconnectInterval = 3000; // 重连间隔时间,单位为毫秒
this.reconnectAttempts = 0; // 重连尝试次数
this.maxReconnectAttempts = 5; // 最大重连尝试次数
}
connect() {
this.socket = new WebSocket(this.url);
this.isAlive = true;
this.socket.onopen = () => {
console.log('WebSocket connection established');
this.reconnectAttempts = 0; // 重连成功后重置重连次数
};
this.socket.onmessage = (event) => {
console.log('Received message:', event.data);
// 处理接收到的消息
};
this.socket.onclose = () => {
console.log('WebSocket connection closed');
this.isAlive = false;
this.reconnect();
};
this.socket.onerror = (error) => {
console.error('WebSocket error:', error);
this.isAlive = false;
this.reconnect();
};
}
reconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
setTimeout(() => {
this.connect();
}, this.reconnectInterval);
} else {
console.error('Max reconnect attempts reached');
}
}
send(message) {
if (this.isAlive && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(message);
console.log('Message sent:', message);
} else {
console.error('WebSocket is not open. Ready state:', this.socket.readyState);
}
}
close() {
if (this.socket) {
this.socket.close();
this.isAlive = false;
}
}
}
export function useWebSocket(url) {
const messages = ref([]);
const wsService = new WebSocketService(url);
const initWebSocket = () => {
wsService.connect();
wsService.socket.onmessage = (event) => {
messages.value.push(event.data);
};
};
onMounted(() => {
initWebSocket();
});
onUnmounted(() => {
wsService.close();
});
return {
messages,
send: (message) => wsService.send(message),
};
}
WebSocketService 类:
constructor(url):初始化 WebSocket 的 URL 和其他配置。connect():创建 WebSocket 连接,并处理连接成功、消息接收、连接关闭和错误事件。reconnect():当连接断开时尝试重新连接,最多尝试 maxReconnectAttempts 次。send(message):发送消息到服务器。close():关闭 WebSocket 连接。useWebSocket 函数:
initWebSocket():初始化 WebSocket 连接并监听消息。onMounted() 和 onUnmounted():分别在组件挂载和卸载时启动和关闭 WebSocket。messages 和 send 方法供外部使用。上一篇:vue数组删除指定位置元素
下一篇:vue3 foreach
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站