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 小时前
计算机网络————(一)HTTP讲解
网络协议·计算机网络·http
小冷爱学习!6 小时前
华为动态路由-OSPF-完全末梢区域
服务器·网络·华为
技术小齐7 小时前
网络运维学习笔记 016网工初级(HCIA-Datacom与CCNA-EI)PPP点对点协议和PPPoE以太网上的点对点协议(此处只讲华为)
运维·网络·学习
看,未来8 小时前
Apipost 与 Postman 工具实践指南:WebSocket调试与动态参数测试
websocket·测试工具·postman
shimly1234569 小时前
tcpdump 用法示例
网络·测试工具·tcpdump
xmweisi10 小时前
【华为】报文统计的技术NetStream
运维·服务器·网络·华为认证
VVVVWeiYee10 小时前
BGP配置华为——路径优选验证
运维·网络·华为·信息与通信
yourkin66611 小时前
TCP...
服务器·网络·tcp/ip
哑巴语天雨13 小时前
前端面试-网络协议篇
websocket·网络协议·http·面试·https
绿色果酱13 小时前
利用Postman和Apipost进行WebSocket调试和文档设计
websocket·测试工具·yapi·postman