vue3+ts封装websocket工具类

封装代码如下:

type EventHandler<T> = (event: T) => void;

class WebSocketTool {
	private ws: WebSocket | null = null;
	private url: string;
	private isOpen: boolean = false;
	private readonly pingTimeout: number = 10000;
	private readonly pongTimeout: number = 1000;
	private pingTimeoutId: ReturnType<typeof setTimeout> | null = null;
	private pongTimeoutId: ReturnType<typeof setTimeout> | null = null;
	private isReconnecting: boolean = false;
	private reconnectTimeout: number = 1000;

	public onopen: EventHandler<Event> | null = null;
	public onclose: EventHandler<CloseEvent> | null = null;
	public onmessage: EventHandler<MessageEvent> | null = null;
	public onerror: EventHandler<Event> | null = null;

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

	private connect(): void {
		this.ws = new WebSocket(this.url);
		this.ws.onopen = event => this.handleOpen(event);
		this.ws.onclose = event => this.handleClose(event);
		this.ws.onerror = event => this.handleError(event);
		this.ws.onmessage = event => this.handleMessage(event);
	}

	private handleOpen(event: Event): void {
		if (this.ws?.readyState !== WebSocket.OPEN) return;
		this.isOpen = true;
		this.onopen?.(event);
		this.startHeartbeat();
	}

	private handleMessage(event: MessageEvent): void {
		this.onmessage?.(event);
		this.resetHeartbeat();
		this.startHeartbeat();
	}

	private handleClose(event: CloseEvent): void {
		this.isOpen = false;
		this.onclose?.(event);
	}

	private handleError(event: Event): void {
		this.onerror?.(event);
		this.reconnect();
	}

	private reconnect(): void {
		if (this.isReconnecting) return;
		this.isReconnecting = true;
		setTimeout(() => {
			this.connect();
			this.isReconnecting = false;
		}, this.reconnectTimeout);
	}

	private startHeartbeat(): void {
		this.resetHeartbeat();
		this.pingTimeoutId = setTimeout(() => {
			this.send({ type: "ping" });
			this.pongTimeoutId = setTimeout(() => {
				console.log("心跳超时,准备重连");
				this.reconnect();
			}, this.pongTimeout);
		}, this.pingTimeout);
	}

	private resetHeartbeat(): void {
		if (this.pingTimeoutId) clearTimeout(this.pingTimeoutId);
		if (this.pongTimeoutId) clearTimeout(this.pongTimeoutId);
	}

	public send(message: any): void {
		if (this.ws && this.isOpen) {
			this.ws.send(JSON.stringify(message)); // 发送消息时转为JSON字符串
		} else {
			console.error("WebSocket 连接未打开,无法发送消息");
		}
	}

	public close(): void {
		this.resetHeartbeat();
		if (this.ws) {
			this.ws.close();
		}
	}
}

export default WebSocketTool;

页面使用时:

// 建立webSocket连接
const ws = new WebSocketTool("/websocket?Authorization=" + token);
ws.onopen = (event: Event) => {
	console.log("WebSocket 连接已打开", event);
};
ws.onmessage = (event: MessageEvent) => {
	const message = JSON.parse(event.data);
	console.log("收到消息:", message);
};
ws.onclose = (event: CloseEvent) => {
	console.log("WebSocket 连接已关闭:", event);
};
ws.onerror = (event: Event) => {
	console.log("WebSocket 错误:", event);
};

页面销毁时:

onBeforeUnmount(() => {
	// 关闭连接
	ws.close();
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值