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();
});
相关推荐
MaximusCoder4 小时前
等保测评命令——Anolis Linux
linux·运维·服务器·网络·经验分享·安全·php
线束线缆组件品替网5 小时前
Adam Tech NPC-6-007-BU网线组件详解
服务器·网络·数码相机·智能路由器·电脑·51单片机·电视盒子
Striver-Diligent5 小时前
您的解决方案准确吗?一种用于增强通信网络可靠性的、面向故障的性能预测方法
网络·深度学习·机器学习·网络性能估计·数字孪生网络·网络预测
cheems95275 小时前
[网络原理]http协议理论基础以及wireshark抓包分析(二)
网络·http·wireshark
双星系统5 小时前
ABB机器人DSQC 679示教器电缆选型与故障排查(附原装型号对照表)
网络·数据库·机器人·工业4.0·工业机器人
炸炸鱼.5 小时前
Nginx 代理与缓存实战:正向、反向及网络层级详解
网络·nginx·缓存
5G行业应用6 小时前
6G未来网络架构ATHENA愿景——《2026韩国SK电讯6G白皮书》
网络·架构
一去不复返的通信er6 小时前
5G系统级仿真
网络·5g
北京耐用通信7 小时前
耐达讯自动化CC-Link IE转DeviceNet网关:破解三菱与欧姆龙PLC协同壁垒的工业实践
人工智能·科技·物联网·网络协议·自动化
cheems95278 小时前
[网络原理]http协议理论基础以及wireshark抓包分析(一)
网络·http·wireshark