欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 类组件化websocket的方法(心跳机制)

类组件化websocket的方法(心跳机制)

2024/10/24 22:17:41 来源:https://blog.csdn.net/qq_46131497/article/details/142103772  浏览:    关键词:类组件化websocket的方法(心跳机制)
/*** WebSocket统一管理*/
export class WebSocketClient {constructor(url) {if (!url) {throw new Error("WebSocket URL is required.");}this.url = url;this.websocket = null;this.listeners = {};this.heartbeatInterval = 30000; // 心跳检测间隔(毫秒)this.reconnectDelay = 10000; // 断线后重连间隔(毫秒)this.pingTimeout = null;this.reconnectTimeout = null;this.isManuallyClosed = false;}/** 初始化 WebSocket 连接 */connect() {this.websocket = new WebSocket(this.url);this.websocket.onopen = () => {// console.log("WebSocket connection opened.");// this.startHeartbeat(); // 开始心跳检测this.dispatch("open");};this.websocket.onmessage = (event) => {const data = JSON.parse(event.data ?? "{}");this.dispatch("message", data);};this.websocket.onclose = () => {// console.log("WebSocket connection closed.");this.dispatch("close");// this.stopHeartbeat(); // 停止心跳检测if (!this.isManuallyClosed) {this.reconnect(); // 自动重连}};this.websocket.onerror = (error) => {console.error("WebSocket error:", error);this.dispatch("error", error);};}// 关闭 WebSocket 连接close() {this.isManuallyClosed = true; // 手动关闭连接时,不进行重连if (this.websocket) {this.websocket.close();}}/*** 添加事件监听函数* @param { 'open' | 'message' | 'close' | 'error' } eventType* @param { (data) => void } callback*/addListener(eventType, callback) {if (!this.listeners[eventType]) {this.listeners[eventType] = [];}this.listeners[eventType].push(callback);}/** 移除事件监听函数 */removeListener(eventType, callback) {if (!this.listeners[eventType]) return;this.listeners[eventType] = this.listeners[eventType].filter((listener) => listener !== callback);}/** 派发事件 */dispatch(eventType, data) {if (!this.listeners[eventType]) return;this.listeners[eventType].forEach((listener) => listener(data));}// 心跳检测 (ping/pong)startHeartbeat() {if (this.pingTimeout) {clearTimeout(this.pingTimeout);}// 定时发送心跳this.pingTimeout = setTimeout(() => {if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {this.websocket.send("ping"); // 发送心跳包console.log("Ping sent to server.");}// 继续心跳this.startHeartbeat();}, this.heartbeatInterval);}// 停止心跳检测stopHeartbeat() {if (this.pingTimeout) {clearTimeout(this.pingTimeout);}}// 自动重连reconnect() {console.log(`正在重连${this.url} ${this.reconnectDelay / 1000} 秒...`);this.reconnectTimeout = setTimeout(() => {this.connect();}, this.reconnectDelay);}send(data) {this.websocket.send(data);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com