class WebSocketUtil { /** * 构造函数,初始化 WebSocket 连接参数 * @param {string} url WebSocket 服务器地址 */ constructor(url) { this.url = url; this.websocket = null; this.onOpenCallback = null; this.onMessageCallback = null; this.onErrorCallback = null; this.onCloseCallback = null; } /** * 连接 WebSocket 服务器 */ connect() { if (this.websocket) { StaticLogger.info("WebSocket connect","WebSocket 已经初始化。") return; } this.websocket = new WebSocket(this.url); // 监听 WebSocket 连接成功事件 this.websocket.onopen = (event) => { StaticLogger.info("WebSocket onopen","WebSocket 连接已打开。") if (this.onOpenCallback) this.onOpenCallback(event); }; // 监听 WebSocket 接收到消息事件 this.websocket.onmessage = (event) => { StaticLogger.info("WebSocket onmessage","WebSocket 接收到消息事件:"+ decodeMessage(event.data).realtimeText); if (this.onMessageCallback) this.onMessageCallback(event); }; // 监听 WebSocket 发生错误事件 this.websocket.onerror = (event) => { StaticLogger.error("WebSocket onerror","WebSocket 发生错误:") if (this.onErrorCallback) this.onErrorCallback(event); }; // 监听 WebSocket 连接关闭事件 this.websocket.onclose = (event) => { StaticLogger.info("WebSocket onclose","WebSocket 连接已关闭:") if (this.onCloseCallback) this.onCloseCallback(event); }; } /** * 发送消息到 WebSocket 服务器 * @param {string} message 需要发送的消息 */ send(message) { StaticLogger.info("WebSocket send","WebSocket 发送消息") if (this.websocket && this.websocket.readyState === WebSocket.OPEN) { this.websocket.send(message); } else { StaticLogger.warn("WebSocket send","WebSocket 连接未打开,无法发送消息。") } } /** * 关闭 WebSocket 连接 */ close() { if (this.websocket) { this.websocket.close(); } } /** * 设置 WebSocket 连接成功时的回调函数 * @param {function} callback 连接成功的回调函数 */ onOpen(callback) { this.onOpenCallback = callback; } /** * 设置 WebSocket 接收到消息时的回调函数 * @param {function} callback 消息接收的回调函数 */ onMessage(callback) { this.onMessageCallback = callback; } /** * 设置 WebSocket 发生错误时的回调函数 * @param {function} callback 发生错误的回调函数 */ onError(callback) { this.onErrorCallback = callback; } /** * 设置 WebSocket 连接关闭时的回调函数 * @param {function} callback 连接关闭的回调函数 */ onClose(callback) { this.onCloseCallback = callback; } }