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 小时前
tcp 和http 网络知识
网络·tcp/ip·http
JavaEdge.1 小时前
LangChain4j HTTP 客户端定制:解锁 LLM API 交互的更多可能性
网络·网络协议·http
Hy行者勇哥1 小时前
形象解释 HTTP 的四种常见请求方式及其中的区别联系
网络·网络协议·http
Cuit小唐1 小时前
TCP 协议:原理、机制与应用
网络·网络协议·tcp/ip
电鱼智能的电小鱼2 小时前
EFISH-SBC-RK3588无人机地面基准站项目
linux·网络·嵌入式硬件·机器人·无人机·边缘计算
电鱼智能的电小鱼2 小时前
基于 EFISH-SBC-RK3588 的无人机环境感知与数据采集方案
linux·网络·嵌入式硬件·数码相机·无人机·边缘计算
Arenaschi3 小时前
SQLite 是什么?
开发语言·网络·python·网络协议·tcp/ip
白帽Gavin3 小时前
SMB协议
网络协议
Gazer_S3 小时前
【HTTP通信:生活中的邮局之旅】
网络协议·http·生活
沧浪之水!4 小时前
【Linux网络】:套接字之UDP
linux·网络·udp