vue3+ts封装websocket工具类

封装代码如下:

TypeScript 复制代码
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 != 1) {
			return;
		}
		this.isOpen = true;
		if (this.onopen) {
			this.onopen(event);
		}
		this.startHeartbeat();
	}

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

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

	private handleError(event: Event): void {
		if (this.onerror) {
			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.pingTimeoutId = setTimeout(() => {
			if (this.isOpen) {
				this.resetHeartbeat();
				return;
			}
			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: string): void {
		if (this.ws && this.isOpen) {
			this.ws.send(message);
		} else {
			console.error("WebSocket 连接未打开,无法发送消息");
		}
	}

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

export default WebSocketTool;

页面使用时:

TypeScript 复制代码
// 建立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);
};

页面销毁时:

TypeScript 复制代码
onBeforeUnmount(() => {
	// 关闭连接
	ws.close();
});
相关推荐
车载测试工程师1 小时前
汽车功能安全-嵌入式软件测试(软件合格性测试)【目的、验证输入、集成&验证要求】11
功能测试·网络协议·测试工具·安全·车载系统·汽车·测试覆盖率
IPdodo全球网络服务2 小时前
什么是IP关联?跨境卖家如何有效避免IP关联?
网络·网络协议·tcp/ip
南棱笑笑生2 小时前
20250711荣品RD-RK3588开发板在Android13下的开机自启动的配置步骤
网络
知北游天4 小时前
Linux:多线程---同步&&生产者消费者模型
java·linux·网络
EasyCVR4 小时前
EasyCVR视频汇聚平台国标接入设备TCP主动播放失败排查指南
网络·tcp/ip·音视频
kfepiza4 小时前
`nmcli con add type vlan`中的: `ifname` , `dev` ,`vlan.parent`, `id`,`vlan.id`
linux·网络协议·tcp/ip
kfepiza4 小时前
Linux的NetworkManager的`nmcli connection add` 笔记250712
linux·网络协议·tcp/ip
刘孬孬沉迷学习4 小时前
5G标准学习笔记15 --CSI-RS测量
网络·笔记·学习·5g·信息与通信·信号处理
敲上瘾5 小时前
传输层协议UDP原理
linux·c语言·网络·网络协议·udp
秃了也弱了。6 小时前
两台电脑通过网线直连形成局域网,共享一台wifi网络实现上网
网络·电脑