wensocket.ts文件中
// src/utils/websocket.ts
import { ref, onunmounted } from 'vue';
interface websocketoptions {
url: string;
protocols?: string | string[];
reconnecttimeout?: number;
}
class websocketservice {
private ws: websocket | null = null;
private callbacks: { [key: string]: function[] } = {};
private reconnecttimeoutms: number = 5000; // 默认5秒重连间隔
constructor(private options: websocketoptions) {}
public open(): void {
this.ws = new websocket(this.options.url, this.options.protocols)
this.ws.addeventlistener('open', this.handleopen);
this.ws.addeventlistener('message', this.handlemessage);
this.ws.addeventlistener('error', this.handleerror);
this.ws.addeventlistener('close', this.handleclose);
}
public close(isactiveclose = false): void {
if (this.ws) {
this.ws.close();
if (!isactiveclose) {
settimeout(() => this.reconnect(), this.reconnecttimeoutms);
}
}
}
public reconnect(): void {
this.open();
}
public on(event: 'message', callback: (data: any) => void): void;
public on(event: 'open' | 'error' | 'close', callback: () => void): void;
public on(event: string, callback: (...args: any[]) => void): void {
if (!this.callbacks[event]) {
this.callbacks[event] = [];
}
this.callbacks[event].push(callback);
}
private handleopen = (): void => {
console.log('websocket连接已建立');
if (this.callbacks.open) {
this.callbacks.open.foreach((cb) => cb());
}
};
private handlemessage = (event: messageevent): void => {
const data = json.parse(event.data);
console.log('websocket接收到消息:', data);
if (this.callbacks.message) {
this.callbacks.message.foreach((cb) => cb(data));
}
};
private handleerror = (error: event): void => {
console.error('websocket错误:', error);
if (this.callbacks.error) {
this.callbacks.error.foreach((cb) => cb(error));
}
};
private handleclose = (): void => {
console.log('websocket连接已关闭');
if (this.callbacks.close) {
this.callbacks.close.foreach((cb) => cb());
if (!this.options.reconnecttimeout) {
this.reconnect();
}
}
};
public send(data: any): void {
if (this.ws && this.ws.readystate === websocket.open) {
this.ws.send(json.stringify(data));
} else {
console.warn('尝试发送消息时websocket未连接');
}
}
}
export default function usewebsocket(options: websocketoptions) {
const wsservice = new websocketservice(options);
onunmounted(() => {
wsservice.close(true);
});
return {
open: wsservice.open.bind(wsservice),
close: wsservice.close.bind(wsservice),
reconnect: wsservice.reconnect.bind(wsservice),
on: wsservice.on.bind(wsservice),
send: wsservice.send.bind(wsservice)
};
使用
import usewebsocket from '@/utils/websocket';//引入websocket.ts文件
import config from '@/config' //引入公共配置文件
const wsoptions = {
url: config.wbbaseurl,
};
const { open, close, reconnect, on, send } = usewebsocket(wsoptions);
onmounted(() => {
open();//在onmounted钩子中调用open函数,链接websocket
// 注册消息接收处理函数
on('message', (data) => {
receivedmessage = data;
console.log(data)
});
});
发表评论