在现代Web应用中,实时通信已成为不可或缺的功能。Vue3作为一个强大的前端框架,结合WebSocket可以轻松实现这一目标。本文将详细介绍如何在Vue3中封装WebSocket,以实现高效、可靠的实时数据传输。

WebSocket类的基本结构

首先,让我们创建一个基本的WebSocket类:

class WebSocketService {
private socket: WebSocket | null = null;
private url: string;

constructor(url: string) {
this.url = url;
}

connect() {
this.socket = new WebSocket(this.url);
this.socket.onopen = this.onOpen.bind(this);
this.socket.onmessage = this.onMessage.bind(this);
this.socket.onclose = this.onClose.bind(this);
this.socket.onerror = this.onError.bind(this);
}

onOpen() {
console.log('WebSocket连接已建立');
}

onMessage(event: MessageEvent) {
console.log('收到消息:', event.data);
}

onClose() {
console.log('WebSocket连接已关闭');
}

onError(error: Event) {
console.error('WebSocket错误:', error);
}

send(data: any) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(data));
} else {
console.error('WebSocket未连接');
}
}

close() {
if (this.socket) {
this.socket.close();
}
}
}
class WebSocketService {
constructor(url) {
this.socket = null;
this.url = url;
}

connect() {
this.socket = new WebSocket(this.url);
this.socket.onopen = this.onOpen.bind(this);
this.socket.onmessage = this.onMessage.bind(this);
this.socket.onclose = this.onClose.bind(this);
this.socket.onerror = this.onError.bind(this);
}

onOpen() {
console.log('WebSocket连接已建立');
}

onMessage(event) {
console.log('收到消息:', event.data);
}

onClose() {
console.log('WebSocket连接已关闭');
}

onError(error) {
console.error('WebSocket错误:', error);
}

send(data) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(data));
} else {
console.error('WebSocket未连接');
}
}

close() {
if (this.socket) {
this.socket.close();
}
}
}

这个基本结构提供了WebSocket的核心功能:连接、发送消息、接收消息和关闭连接。

添加心跳机制

为了保持连接的稳定性,我们可以添加心跳机制:

class WebSocketService {
// ... 前面的代码 ...

private heartbeatTimer: number | null = null;
private heartbeatInterval = 30000; // 30秒

startHeartbeat() {
this.heartbeatTimer = setInterval(() => {
this.send({ type: 'heartbeat' });
}, this.heartbeatInterval);
}

stopHeartbeat() {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}

connect() {
// ... 连接代码 ...
this.startHeartbeat();
}

onClose() {
console.log('WebSocket连接已关闭');
this.stopHeartbeat();
}
}
class WebSocketService {
constructor(url) {
// ... 前面的代码 ...
this.heartbeatTimer = null;
this.heartbeatInterval = 30000; // 30秒
}

startHeartbeat() {
this.heartbeatTimer = setInterval(() => {
this.send({ type: 'heartbeat' });
}, this.heartbeatInterval);
}

stopHeartbeat() {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}

connect() {
// ... 连接代码 ...
this.startHeartbeat();
}

onClose() {
console.log('WebSocket连接已关闭');
this.stopHeartbeat();
}
}

心跳机制可以帮助我们及时发现连接断开的情况,并保持连接的活跃状态。

实现断线重连

为了提高可靠性,我们还需要添加断线重连功能:

class WebSocketService {
// ... 前面的代码 ...

private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
private reconnectInterval = 5000; // 5秒

reconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
setTimeout(() => {
this.connect();
}, this.reconnectInterval);
} else {
console.error('达到最大重连次数,连接失败');
}
}

onClose() {
console.log('WebSocket连接已关闭');
this.stopHeartbeat();
this.reconnect();
}

onOpen() {
console.log('WebSocket连接已建立');
this.reconnectAttempts = 0;
this.startHeartbeat();
}
}
class WebSocketService {
constructor(url) {
// ... 前面的代码 ...
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectInterval = 5000; // 5秒
}

reconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
setTimeout(() => {
this.connect();
}, this.reconnectInterval);
} else {
console.error('达到最大重连次数,连接失败');
}
}

onClose() {
console.log('WebSocket连接已关闭');
this.stopHeartbeat();
this.reconnect();
}

onOpen() {
console.log('WebSocket连接已建立');
this.reconnectAttempts = 0;
this.startHeartbeat();
}
}

这段代码实现了断线重连机制,在连接关闭时自动尝试重新连接,直到达到最大重连次数。

在Vue3中使用

最后,我们可以在Vue3组件中使用这个封装好的WebSocket服务:

<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue';
import WebSocketService from './WebSocketService';

const ws = new WebSocketService('ws://your-websocket-server-url');

onMounted(() => {
ws.connect();
});

onUnmounted(() => {
ws.close();
});

// 发送消息示例
function sendMessage() {
ws.send({ type: 'chat', content: 'Hello, WebSocket!' });
}
</script>
<script setup>
import { onMounted, onUnmounted } from 'vue';
import WebSocketService from './WebSocketService';

const ws = new WebSocketService('ws://your-websocket-server-url');

onMounted(() => {
ws.connect();
});

onUnmounted(() => {
ws.close();
});

// 发送消息示例
function sendMessage() {
ws.send({ type: 'chat', content: 'Hello, WebSocket!' });
}
</script>

这样,我们就完成了一个功能完善的WebSocket封装,它包含了基本的连接管理、心跳机制和断线重连功能。在Vue3项目中使用这个封装,可以大大简化WebSocket的使用,提高开发效率和应用的可靠性。

记住,在实际应用中,你可能还需要根据具体需求进行进一步的定制,比如添加消息队列、错误处理等功能。希望这篇文章能够帮助你在Vue3项目中更好地使用WebSocket!