封装WebSocket.ts
// '@/utils/WebSocketService';
export class WebSocketService {
private socket: WebSocket | null = null;
private url: string;
constructor(url: string) {
this.url = url;
}
public connect(): void {
if (this.socket) {
console.log('WebSocket已经连接上了');
return;
}
this.socket = new WebSocket(this.url);
this.socket.onopen = () => {
console.log('已连接WebSocket');
// 可以在这里发送一些初始化消息
};
this.socket.onmessage = (event) => {
console.log('接收到的消息:', event.data);
// 通过事件派发等方式通知 Vue 组件
window.dispatchEvent(
new CustomEvent('onmessageWS', {
detail: {
data: event.data
}
})
);
};
this.socket.onerror = (error) => {
console.error('WebSocket中的错误:', error);
};
this.socket.onclose = () => {
console.log('已断开WebSocket连接');
// 可以尝试重新连接
};
}
public disconnect(): void {
if (this.socket) {
this.socket.close();
this.socket = null;
}
}
// 可以添加其他方法,如发送消息
public sendMessage(message: string): void {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(message);
} else {
console.error('WebSocket未连接');
}
}
}
使用WebSocket
<template>
<div>
<h1>WebSocket Demo</h1>
<el-input v-model="messageToSend" />
<button @click="sendMessageToServer">Send Message to Server</button>
</div>
</template>
<script lang="ts" setup>
import { defineComponent, onMounted, onUnmounted, ref } from 'vue';
import { WebSocketService } from '@/utils/WebSocketService';
const wsService = new WebSocketService('ws://x-tool.online:8082/ws');
const messageToSend = ref(''); // 假设你有一个输入框来输入消息,这里用 ref 代替
// 监听事件
window.addEventListener('onmessageWS', (event: any) => {
console.log('vue组件接受到的数据', event.detail.data);
});
// 组件挂载时连接 WebSocket
onMounted(() => {
wsService.connect();
});
// 组件卸载时断开 WebSocket
onUnmounted(() => {
wsService.disconnect();
});
// 发送消息到服务器的方法
const sendMessageToServer = () => {
wsService.sendMessage(messageToSend.value);
};
</script>