uniapp。封装uniapp内置的websocket,并且增加是否启用心跳检测、断线重连次数
- User
uniapp。封装uniapp内置的websocket,并且增加是否启用心跳检测、断线重连次数
- Assistant
在 UniApp 中封装 WebSocket 并添加心跳检测和断线重连功能,你可以通过封装一个 JavaScript 模块来实现。以下是一个示例实现:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; // 心跳间隔 this.reconnectInterval = options.reconnectInterval || 5000; // 重连间隔 this.maxReconnectAttempts = options.maxReconnectAttempts || 5; // 最大重连次数 this.reconnectAttempts = 0; this.enableHeartbeat = options.enableHeartbeat || false; // 是否启用心跳检测 this.ws = null; this.heartbeatTimer = null; this.messageCallback = options.onMessage || null; this.connect(); } connect() { this.ws = uni.connectSocket({ url: this.url, complete: () => { console.log('WebSocket connection attempt finished'); } }); this.ws.onOpen(() => { console.log('WebSocket connected'); this.reconnectAttempts = 0; if (this.enableHeartbeat) { this.startHeartbeat(); } }); this.ws.onMessage((message) => { console.log('WebSocket message received:', message.data); if (this.messageCallback) { this.messageCallback(message); } // Reset heartbeat on message, assuming receiving any message is equivalent to pong if (this.enableHeartbeat) { this.startHeartbeat(); } }); this.ws.onClose(() => { console.log('WebSocket closed'); this.reconnect(); }); this.ws.onError((error) => { console.error('WebSocket error:', error); this.reconnect(); }); } reconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; console.log(`Reconnecting... (${this.reconnectAttempts})`); setTimeout(() => this.connect(), this.reconnectInterval); } else { console.error('Max reconnect attempts reached'); } } startHeartbeat() { if (this.heartbeatTimer) { clearTimeout(this.heartbeatTimer); } this.heartbeatTimer = setTimeout(() => { this.sendHeartbeat(); }, this.heartbeatInterval); } sendHeartbeat() { if (this.ws && this.ws.readyState === 1) { // WebSocket.OPEN console.log('Sending heartbeat'); this.ws.send({ data: JSON.stringify({ type: 'heartbeat' }), success: () => this.startHeartbeat(), fail: (error) => console.error('Heartbeat failed', error) }); } } sendMessage(data) { if (this.ws && this.ws.readyState === 1) { // WebSocket.OPEN this.ws.send({ data: JSON.stringify(data), success: () => console.log('Message sent successfully'), fail: (error) => console.error('Message send failed', error) }); } else { console.error('WebSocket is not open'); } } close() { if (this.ws) { this.ws.close(); } if (this.heartbeatTimer) { clearTimeout(this.heartbeatTimer); } } } export default UniAppWebSocket;用法示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://your-websocket-url', { enableHeartbeat: true, heartbeatInterval: 10000, reconnectInterval: 5000, maxReconnectAttempts: 3, onMessage: (message) => { console.log('Received:', message.data); } }); // 发送消息 ws.sendMessage({ action: 'some_action', data: 'your_data_here' }); // 在适当的时候关闭连接 // ws.close();这个实现提供了心跳检测和自动重连功能,并允许配置心跳间隔和最大重连次数。如果启用了心跳检测,它会在没有接收到消息时定期发送心跳信息以保持连接状态。
- User
这个封装很差
- Assistant
抱歉之前的回答没能满足你的要求。下面是一个更加完善、详细的 UniApp WebSocket 封装示例,包含心跳检测和断线重连功能:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; // 心跳检测间隔 this.reconnectInterval = options.reconnectInterval || 5000; // 重连间隔 this.maxReconnectAttempts = options.maxReconnectAttempts || 5; // 最大重连次数 this.reconnectAttempts = 0; this.enableHeartbeat = options.enableHeartbeat || false; // 是否启用心跳检测 this.webSocket = null; this.heartbeatTimer = null; this.reconnectTimer = null; this.onOpen = options.onOpen || function() {}; this.onMessage = options.onMessage || function() {}; this.onClose = options.onClose || function() {}; this.onError = options.onError || function() {}; // 初始化连接 this.connect(); } connect() { if (this.webSocket) { this.clearWebSocket(); } this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => { console.log('WebSocket connected'); this.onOpen(); this.reconnectAttempts = 0; // 重置重连计数 if (this.enableHeartbeat) { this.startHeartbeat(); } }); this.webSocket.onMessage((res) => { console.log('WebSocket message received:', res.data); this.onMessage(res); if (this.enableHeartbeat) { this.startHeartbeat(); // 重置心跳 } }); this.webSocket.onClose(() => { console.log('WebSocket closed'); this.onClose(); if (this.enableHeartbeat) { this.clearHeartbeat(); } this.reconnect(); }); this.webSocket.onError((err) => { console.error('WebSocket error:', err); this.onError(err); if (this.enableHeartbeat) { this.clearHeartbeat(); } this.reconnect(); }); } reconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; console.log(`Reconnecting... (Attempt ${this.reconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { console.error('Max reconnect attempts reached'); } } startHeartbeat() { if (this.heartbeatTimer) { clearTimeout(this.heartbeatTimer); } this.heartbeatTimer = setTimeout(() => { if (this.webSocket && this.webSocket.readyState === 1) { // WebSocket.OPEN 状态 this.webSocket.send({ data: JSON.stringify({ type: 'heartbeat' }) }); console.log('Heartbeat sent'); } this.startHeartbeat(); // 循环心跳 }, this.heartbeatInterval); } clearHeartbeat() { if (this.heartbeatTimer) { clearTimeout(this.heartbeatTimer); this.heartbeatTimer = null; } } sendMessage(data) { if (this.webSocket && this.webSocket.readyState === 1) { // WebSocket.OPEN 状态 this.webSocket.send({ data: JSON.stringify(data), success: () => console.log('Message sent successfully'), fail: (error) => console.error('Message send failed', error) }); } else { console.error('WebSocket is not open'); } } close() { if (this.webSocket) { this.clearWebSocket(); this.webSocket.close(); } this.clearHeartbeat(); if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } clearWebSocket() { if (this.webSocket) { this.webSocket.onOpen = null; this.webSocket.onMessage = null; this.webSocket.onClose = null; this.webSocket.onError = null; } } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; // 初始化 WebSocket const ws = new UniAppWebSocket('wss://your-server-url', { enableHeartbeat: true, heartbeatInterval: 10000, // 10秒 reconnectInterval: 5000, // 5秒 maxReconnectAttempts: 5, onOpen: () => console.log('WebSocket opened'), onMessage: (message) => console.log('Received:', message.data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error', error) }); // 发送消息 ws.sendMessage({ action: 'some_action', data: 'your_data_here' }); // 在需要时关闭连接 // ws.close();这个实现更加结构化,确保了在使用 WebSocket 时处理事件绑定、重连逻辑和心跳检测,并提供了一些回调用于处理连接操作结果。请根据需要进行调整和扩展。
- User
这个封装也很差
- Assistant
非常抱歉之前的回答未能达到您的期望。下面是一个更为改进的封装,它试图更好地处理心跳包、重连逻辑,以及 WebSocket 的状态管理:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; // 心跳间隔 this.reconnectInterval = options.reconnectInterval || 5000; // 重连间隔 this.maxReconnectAttempts = options.maxReconnectAttempts || 5; // 最大重连次数 this.enableHeartbeat = options.enableHeartbeat || false; // 是否启用心跳 this.currentReconnectAttempts = 0; this.isConnected = false; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; // 回调函数 this.onOpen = options.onOpen || (() => {}); this.onMessage = options.onMessage || (() => {}); this.onClose = options.onClose || (() => {}); this.onError = options.onError || (() => {}); this.connect(); } connect() { if (this.isConnected) return; this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => { this.isConnected = true; this.currentReconnectAttempts = 0; this.onOpen(); if (this.enableHeartbeat) { this.startHeartbeat(); } }); this.webSocket.onMessage((message) => { this.onMessage(message); if (this.enableHeartbeat) { this.resetHeartbeat(); } }); this.webSocket.onClose(() => { this.isConnected = false; this.onClose(); if (!this.isManualClose) { this.reconnect(); } }); this.webSocket.onError((error) => { this.isConnected = false; this.onError(error); if (!this.isManualClose) { this.reconnect(); } }); } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.reconnectTimer = setTimeout(() => { this.connect(); }, this.reconnectInterval); } else { console.error('Max reconnect attempts reached'); } } startHeartbeat() { if (this.heartbeatTimer) clearInterval(this.heartbeatTimer); this.heartbeatTimer = setInterval(() => { if (this.isConnected) { this.webSocket.send({ data: JSON.stringify({ type: 'ping' }), }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } sendMessage(data) { if (this.isConnected) { this.webSocket.send({ data: JSON.stringify(data), success: () => console.log('Message sent successfully'), fail: (error) => console.error('Message send failed', error), }); } else { console.error('WebSocket is not open'); } } close() { if (this.webSocket) { this.isManualClose = true; this.webSocket.close(); } if (this.heartbeatTimer) clearInterval(this.heartbeatTimer); if (this.reconnectTimer) clearTimeout(this.reconnectTimer); } } export default UniAppWebSocket;用法示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 10000, reconnectInterval: 5000, maxReconnectAttempts: 5, onOpen: () => console.log('WebSocket opened'), onMessage: (message) => console.log('Received:', message.data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息 ws.sendMessage({ action: 'some_action', data: 'your_data_here' }); // 在需要时主动关闭连接 // ws.close();这个版本采取更清晰的状态管理,把握 WebSocket 的连接状态,并分别处理重连的最大次数,防止无限重连。希望这个版本能更符合您的需求。如果还有任何需要改进的地方,请随时告诉我。
- User
还是很差,不完善
- Assistant
感谢您的耐心和反馈。为了进一步完善 WebSocket 封装,我们可以确保支持以下功能:
- 严格的心跳检测和实时重置。
- 更高效的断线重连逻辑。
- 明确的状态管理。
- 统一事件处理格式。
以下是一个更为全面的 WebSocket 封装示例:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || Infinity; this.enableHeartbeat = options.enableHeartbeat !== false; this.currentReconnectAttempts = 0; this.isConnected = false; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; this.connect(); } connect() { this.isManualClose = false; this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(this.handleOpen.bind(this)); this.webSocket.onMessage(this.handleMessage.bind(this)); this.webSocket.onClose(this.handleClose.bind(this)); this.webSocket.onError(this.handleError.bind(this)); } handleOpen() { this.isConnected = true; this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.eventHandlers.message(message); if (this.enableHeartbeat) { this.resetHeartbeat(); } } handleClose() { this.isConnected = false; this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.isConnected = false; this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.reconnectTimer = setTimeout(() => { this.connect(); }, this.reconnectInterval); } else { console.error('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected) { this.webSocket.send({ data: JSON.stringify({ type: 'ping' }), success: () => console.log('Heartbeat sent'), fail: (error) => console.error('Heartbeat send failed', error), }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } sendMessage(data) { if (this.isConnected) { this.webSocket.send({ data: JSON.stringify(data), success: () => console.log('Message sent successfully'), fail: (error) => console.error('Message send failed', error), }); } else { console.error('WebSocket is not open'); } } close() { if (this.webSocket) { this.isManualClose = true; this.clearHeartbeat(); this.webSocket.close(); } if (this.reconnectTimer) clearTimeout(this.reconnectTimer); } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 10000, reconnectInterval: 5000, maxReconnectAttempts: 10, onOpen: () => console.log('WebSocket opened'), onMessage: (message) => console.log('Received:', message.data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息 ws.sendMessage({ action: 'some_action', data: 'your_data_here' }); // 在需要时主动关闭连接 // ws.close();这个版本增加了更多的控制和管理机制,并改善了事件管理与回调机制,确保对 WebSocket 状态的细粒度控制和对心跳的严格维护。希望这个版本更符合您的要求。感谢您的耐心,欢迎给出更多反馈!
- User
还是很差,不完善
- Assistant
对不起我之前的回答未能满足您的需求。为了提高代码的健壮性和易用性,让我们尝试从头构建一个更完善的 WebSocket 封装:
class UniAppWebSocket { constructor(url, options = {}) { // 配置 this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; // 默认10秒 this.reconnectInterval = options.reconnectInterval || 5000; // 默认5秒 this.maxReconnectAttempts = options.maxReconnectAttempts || 10; // 默认10次 this.enableHeartbeat = options.enableHeartbeat !== false; // 默认启用心跳 // 状态管理 this.currentReconnectAttempts = 0; this.isConnected = false; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; // 事件回调 this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; // 初始化连接 this.connect(); } connect() { this.isManualClose = false; this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { console.log('WebSocket connected'); this.isConnected = true; this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { console.log('WebSocket message received:', message.data); this.eventHandlers.message(message); this.resetHeartbeat(); } handleClose() { console.log('WebSocket closed'); this.isConnected = false; this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { console.error('WebSocket error:', error); this.isConnected = false; this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; console.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => { this.connect(); }, this.reconnectInterval); } else { console.error('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected) { this.webSocket.send({ data: JSON.stringify({ type: 'ping' }), success: () => console.log('Heartbeat sent'), fail: (error) => console.error('Heartbeat send failed', error), }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } sendMessage(data) { if (this.isConnected) { this.webSocket.send({ data: JSON.stringify(data), success: () => console.log('Message sent'), fail: (error) => console.error('Message send failed', error), }); } else { console.error('WebSocket is not open'); } } close() { if (this.webSocket) { this.isManualClose = true; this.clearHeartbeat(); this.webSocket.close(); } if (this.reconnectTimer) clearTimeout(this.reconnectTimer); } } export default UniAppWebSocket;主要变化和改进:
- 结构清晰:通过函数组织代码更易读,确保每个功能块的清晰性。
- 状态管理:使用状态变量(如
isConnected、isManualClose)确保状态完整定义。 - 事件回调:通过
eventHandlers保存事件处理程序,以简化逻辑。 - 心跳与重连:实现中捕获各种状态和错误,并通过可控的心跳和重连逻辑确保连接的稳定。
使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, onOpen: () => console.log('WebSocket opened'), onMessage: (message) => console.log('Received:', message.data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息 ws.sendMessage({ action: 'some_action', data: 'your_data_here' }); // 在需要时主动关闭连接 // ws.close();请根据实际应用需求调整相关参数和实现逻辑。如果还有其他需要改进的地方或者特定需求,请继续告知!
- User
你还是不明白,功能上应该扩展
- Assistant
非常抱歉没能准确理解您的要求。为了让这个 WebSocket 封装更加完善并满足更复杂的应用场景,我将从以下几个方面进行功能扩展:
- 添加状态回调:通知外部有关连接状态的变化,更好地处理连接生命周期。
- 支持自定义消息格式和解析:允许用户自定义消息的封装和解析,以支持不同协议。
- 提供连接状态检查:增加检查函数,方便外部组件随时获取当前连接状态。
- 支持外部事件绑定:通过事件管理系统为更多操作提供钩子。
- 日志管理:提供灵活可控的日志输出功能,支持用户自定义处理日志以便在生产环境中关闭日志或发送到其他日志管理系统。
下面是一个更为全面的综合实现:
class UniAppWebSocket { constructor(url, options = {}) { // 初始化配置 this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || Infinity; this.enableHeartbeat = options.enableHeartbeat !== false; this.debug = options.debug || false; // 控制是否输出日志 // 状态管理 this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; // 初始化事件管理器 this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), connectAttempt: options.onConnectAttempt || (() => {}), disconnect: options.onDisconnect || (() => {}), }; // 自定义消息编码和解码 this.encodeMessage = options.encodeMessage || JSON.stringify; this.decodeMessage = options.decodeMessage || JSON.parse; // 开始连接 this.connect(); } log(...args) { if (this.debug) { console.log(...args); } } connect() { this.isManualClose = false; this.eventHandlers.connectAttempt(this.currentReconnectAttempts); this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = this.decodeMessage(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); this.eventHandlers.disconnect(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.webSocket && this.webSocket.readyState === 1) { // 1 = WebSocket.OPEN this.webSocket.send({ data: this.encodeMessage({ type: 'ping' }), success: () => this.log('Heartbeat sent'), fail: (error) => this.log('Heartbeat send failed', error), }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } sendMessage(data) { if (this.webSocket && this.webSocket.readyState === 1) { // 1 = WebSocket.OPEN this.webSocket.send({ data: this.encodeMessage(data), success: () => this.log('Message sent'), fail: (error) => this.log('Message send failed', error), }); } else { this.log('WebSocket is not open'); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; // 1 = WebSocket.OPEN } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, debug: true, // 启用调试 onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), onConnectAttempt: (attempt) => console.log(`Attempting to connect: ${attempt}`), onDisconnect: () => console.log('Disconnected from WebSocket'), encodeMessage: (msg) => JSON.stringify(msg), decodeMessage: (msg) => JSON.parse(msg), }); // 发送消息 ws.sendMessage({ action: 'some_action', data: 'your_data_here' }); // 检查连接状态 console.log(`WebSocket is ${ws.isConnected() ? 'connected' : 'disconnected'}`); // 在需要时主动关闭连接 // ws.close();设计要点:
- 事件回调强化:增加了更多的连接状态和事件的钩子。
- 灵活的消息处理:用户可以传入自定义的消息编码和解码方法,以适应不同的数据结构和协议。
- 连接状态查询:通过
isConnected方法来随时获取当前的连接状态。 - 日志控制:可以通过
debug标志来控制是否输出详细的日志。
如果这次的实现还是不符合您的需求,请您指出具体的改进方向或功能需求,我会尽力改进!
- User
你这个过度扩展了。比之前的差了。在以前的基础上,你应该关注的是消息发送的问题。用户使用时,如果消息发送成功或失败可能会执行不同的业务
- Assistant
感谢您的澄清和指导。理解您希望更多关注消息发送的成功与失败,并在此基础上执行不同的业务逻辑。为了支持这一点,我们需要允许用户在发送消息时传入成功和失败的回调。
以下是更新后的 WebSocket 封装,它显式支持为每个消息添加成功和失败的回调函数:
class UniAppWebSocket { constructor(url, options = {}) { // 初始化配置 this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.debug = options.debug || false; // 状态管理 this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; // 初始化事件管理器 this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; this.connect(); } log(...args) { if (this.debug) { console.log(...args); } } connect() { this.isManualClose = false; this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } sendMessage(data, onSuccess, onError) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, debug: true, onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息,并在成功或失败后执行回调 ws.sendMessage( { action: 'some_action', data: 'your_data_here' }, () => console.log('Message successfully sent!'), (error) => console.log('Message failed to send:', error) ); // 在需要时主动关闭连接 // ws.close();改进要点:
- 在
sendMessage方法中添加了onSuccess和onError回调,这样用户可以根据发送是否成功执行不同的业务逻辑。 - 简化了设计,专注于消息通信,确保功能模块化并且灵活。
- 维护对连接状态的内置检查,增强健壮性和稳定性。
请根据特定需求进一步调整和定制。如果有更多功能需求或其他具体问题,请随时指出!
- 在
- User
或者可以再加个消息队列,在适当的时候将未成功发送的的消息再次发送?
- Assistant
增加消息队列功能可以提升系统的可靠性,确保消息在发送失败时能被再次尝试发送。这对于网络不稳定或 WebSocket 连接暂时不可用的情况特别有用。下面是对现有 WebSocket 封装进行扩展的示例,增加了简单的消息队列以保存和重试发送失败的消息:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; // 消息队列 this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; this.connect(); } log(...args) { if (this.debug) { console.log(...args); } } connect() { this.isManualClose = false; this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; this.eventHandlers.open(); this.processQueue(); // 尝试重新发送队列中的消息 if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError) { this.messageQueue.push({ data, onSuccess, onError }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError } = this.messageQueue.shift(); this.sendMessage(data, onSuccess, onError); } } sendMessage(data, onSuccess, onError) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); this.enqueueMessage(data, onSuccess, onError); // 将消息重新入队 if (onError) onError(error); }, }); } else { this.log('WebSocket is not open, enqueueing message'); this.enqueueMessage(data, onSuccess, onError); if (onError) onError(new Error('WebSocket is not open, message queued')); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;说明:
- 消息队列:未能成功发送的消息会被保存到
messageQueue中。 - 重试发送:在连接重新打开时 (
handleOpen),处理并重试发送队列中的消息。 - 入队操作:消息发送失败时被放入队列中,并在
processQueue中重新发送。
使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, debug: true, onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息,并在成功或失败后执行回调 ws.sendMessage( { action: 'some_action', data: 'your_data_here' }, () => console.log('Message successfully sent!'), (error) => console.log('Message failed to send:', error) ); // 在需要时主动关闭连接 // ws.close();该实现保证消息即使在连接不可用时也不会丢失,确保在连接恢复后能够继续发送。请根据您的具体要求进一步调整和优化。有任何其他要求,请随时告诉我。
- 消息队列:未能成功发送的消息会被保存到
- User
消息队列应该是可选的的
- Assistant
为了使消息队列功能可选,可以通过在初始化时提供一个选项来决定是否启用消息队列。下面是一个更新后的实现,其中将消息队列功能设计为可选项:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; // 控制是否启用消息队列 this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; // 存储待发送的消息 this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; this.connect(); } log(...args) { if (this.debug) { console.log(...args); } } connect() { this.isManualClose = false; this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); // 连接成功后处理队列 } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError) { this.messageQueue.push({ data, onSuccess, onError }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError } = this.messageQueue.shift(); this.sendMessage(data, onSuccess, onError); } } sendMessage(data, onSuccess, onError) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError); // 只有启用队列时才重新入队 } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;说明:
- 队列可控:通过
enableQueue选项让消息队列功能可选。 - 条件入队:在启用消息队列后才会在消息发送失败时将消息入队。
- 发送失败重试:在下一次连接成功后,自动从队列处理未发送的消息。
使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, enableQueue: true, // 启用消息队列 debug: true, onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息 ws.sendMessage( { action: 'some_action', data: 'your_data_here' }, () => console.log('Message successfully sent!'), (error) => console.error('Message failed to send:', error) ); // 在需要时主动关闭连接 // ws.close();这样设计使得消息队列功能可以按需启用,保持了组件的灵活性。如果您有其他的具体需求或改进建议,请告诉我。
- 队列可控:通过
- User
处理消息队列时,是否执行原消息的回调也是统一可选的
- Assistant
为了实现消息队列再次发送时是否执行原消息回调的可选功能,我们可以在消息队列中保存一个标志,指示是否在重发时调用回调。通过这种方式,用户可以在发送消息时指定他们的偏好。
我们将添加一个
callBackOnRetry参数,以控制在重试的时候是否执行原始的回调:class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; this.connect(); } log(...args) { if (this.debug) { console.log(...args); } } connect() { this.isManualClose = false; this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, enableQueue: true, debug: true, onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息,并在成功或失败后执行回调,重试时不再调用回调 ws.sendMessage( { action: 'some_action', data: 'your_data_here' }, () => console.log('Message successfully sent!'), (error) => console.error('Message failed to send:', error), false // 处理队列中的消息重试时不调用回调 ); // 在需要时主动关闭连接 // ws.close();设计说明:
callBackOnRetry参数:当调用sendMessage时,可以指定在重试场景下是否使用原始的成功或失败回调。- 消息队列:默认是启用的,但可以在应用初始化时关闭队列功能。
- 灵活性:开发者可以根据需要控制队列操作时的行为。
如果您有任何其他要求或意见,请随时告诉我!
- User
现在再考虑个问题,如果我手动关闭连接,以后再手动连接呢?
- Assistant
为了支持手动关闭连接并在之后手动重新连接,我们需要:
- 提供一个公共的方法来手动重新连接 WebSocket。
- 确保手动关闭状态和自动重连逻辑不冲突。
- 清除所有的定时器和状态以保证重新连接的干净。
首先,我们要确保在手动关闭连接时不会触发自动重连机制,并能通过公共接口再次进行连接。以下是更新后的代码:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; this.connect(); } log(...args) { if (this.debug) { console.log(...args); } } connect() { if (this.isManualClose) { this.log('Connection was manually closed. Please use `reconnect` to connect again.'); return; } this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { this.isManualClose = false; if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } reconnectManually() { if (!this.isConnected()) { this.isManualClose = false; // 重置手动关闭状态 this.connect(); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, enableQueue: true, debug: true, onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 发送消息 ws.sendMessage( { action: 'some_action', data: 'your_data_here' }, () => console.log('Message successfully sent!'), (error) => console.error('Message failed to send:', error), false // 处理队列中的消息重试时不调用回调 ); // 手动关闭连接 ws.close(); // 之后,在需要时手动重新连接 ws.reconnectManually();说明:
- 手动关闭:调用
close方法会标记连接为手动关闭,并且不会触发自动重连。 - 手动重连:使用
reconnectManually方法可以在手动关闭后重新发起连接。 - 重连清除标志:在
reconnectManually中确保isManualClose标志被重置,以允许新的连接。
您可以根据需要进一步调整这些功能以适应您的具体需求。如果有其他建议或要求,欢迎随时告知。
- User
有必要再增加reconnectManually? 优化connect的代码,用connect不行?
- Assistant
您说得对,我们可以通过优化
connect方法的逻辑来实现手动重新连接的功能,而不必额外添加reconnectManually方法。以下是调整和优化后的代码:class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = true; // 初始化时为手动关闭状态 this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; // 创建实例时不主动连接,需要手动连接调用 connect() } log(...args) { if (this.debug) { console.log(...args); } } connect() { if (!this.isManualClose) { this.log('Already connected or connecting, no need to reconnect.'); return; } this.isManualClose = false; // 标记为非手动关闭,以允许自动重连 this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; const ws = new UniAppWebSocket('wss://example.com', { enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, enableQueue: true, debug: true, onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 手动进行连接 ws.connect(); // 发送消息 ws.sendMessage( { action: 'some_action', data: 'your_data_here' }, () => console.log('Message successfully sent!'), (error) => console.error('Message failed to send:', error), false // 处理队列中的消息重试时不调用回调 ); // 手动关闭连接 ws.close(); // 之后,手动重新连接 ws.connect();说明:
- 手动连接:在需要时通过
ws.connect()方法主动建立连接。 - 连接状态检查:
connect()方法会检查当前状态避免重复连接。 - 手动关闭与重新连接:通过将
isManualClose设为true控制自动重连逻辑,并在手动调用connect()时重置标志。
这种方法提供了更多的控制灵活性,能够通过统一的
connect方法来实现手动关闭后的重新连接。欢迎您继续提出建议或需求! - 手动连接:在需要时通过
- User
if (!this.isManualClose) { this.log('Already connected or connecting, no need to reconnect.'); return; }
this.isManualClose = false; // 标记为非手动关闭,以允许自动重连。--------- this.isManualClose = false,在上面就return了吧?怎么自动重连? - Assistant
感谢指出这一问题。在
connect方法中,逻辑需要确保在适当的状态下进行连接,并且支持在手动关闭后重新连接。当前逻辑中确实存在问题,因为我们希望能够通过connect方法重新激活 WebSocket 即使在之前手动关闭。这里是修正之后的代码逻辑:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; // 初始化时不自动连接 } log(...args) { if (this.debug) { console.log(...args); } } connect() { // 若已经连接或正在尝试重连,不需要重复操作 if (this.isConnected() || this.reconnectTimer) { this.log('Already connected or attempting reconnect.'); return; } this.isManualClose = false; // 准备进行连接或重连 this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); // 仅在非手动关闭时进行重连 if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); // 仅在非手动关闭时进行重连 if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;说明:
connect方法:确保在未连接时可以被调用并建立连接,同时避免重复调用在已连接或正在尝试重连时的操作。- 手动关闭状态:
isManualClose仅在手动调用close方法时设为true,以防止自动重连。 - 自动重连:在
handleClose和handleError中仅在非手动关闭时尝试重连。 - 连接检查:
isConnected()方法用于检查当前的 WebSocket 状态。
可以通过调整
options参数来适应具体需求。希望这次的优化更符合您的期望。如有进一步问题或建议,请随时告知。 - User
手动关闭,应该将maxReconnectAttempts设置为初始值,你认为如何?是否合适?
- Assistant
这个建议是合适的。例如,在手动关闭 WebSocket 后,如果用户选择重新连接,重连的尝试次数应该从零开始。这样做的好处是确保连接逻辑在手动关闭和重新连接之间保持一致,并且不会受到之前自动重连逻辑的影响(如之前的尝试次数):
下面是如何实现这个行为的更新后的代码:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; // 初始化时不自动连接 } log(...args) { if (this.debug) { console.log(...args); } } connect() { if (this.isConnected() || this.reconnectTimer) { this.log('Already connected or attempting reconnect.'); return; } this.isManualClose = false; // 准备进行连接或重连 this.webSocket = uni.connectSocket({ url: this.url }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.currentReconnectAttempts = 0; // 重置重连计数器 this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;说明:
- 重置尝试计数器:在
close方法中,将currentReconnectAttempts重置为 0。这确保当您手动关闭连接后,再次调用connect时重连尝试计数将从零开始。 - 状态控制:
isManualClose标志用于控制是否应该触发自动重连逻辑。
这种方法确保了在关闭后重置尝试计数,并在需要时可以手动重新发起连接。如果还有需要调整的地方或者进一步的建议,请告诉我!
- 重置尝试计数器:在
- User
我们继续,可能会在header头中带上token供后端验证,并且可能会更换token
- Assistant
在 WebSocket 连接中通过 headers 发送 token 来进行身份验证是一种常见的做法。虽然原生 WebSocket 协议不支持将 HTTP headers 设置在帧内,但许多库和平台提供了扩展功能以支持这种需求。在 UniApp 中,可以通过参数设置在初始化连接时加入自定义 headers,包括 token。
此外,在这种情况下,如果 token 发生变化,我们需要提供一种机制来更新 token 并重新连接 WebSocket。
下面是如何实现这种功能的修改版代码:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.token = options.token || ''; // 初始 token this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; // 初始化时不自动连接 } log(...args) { if (this.debug) { console.log(...args); } } connect() { if (this.isConnected() || this.reconnectTimer) { this.log('Already connected or attempting reconnect.'); return; } this.isManualClose = false; // 准备进行连接或重连 this.webSocket = uni.connectSocket({ url: this.url, header: { Authorization: `Bearer ${this.token}`, // 将 token 添加到 headers 中 }, }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.currentReconnectAttempts = 0; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } } updateToken(newToken) { this.token = newToken; this.log('Token updated:', this.token); // 如有必要,更新 token 后重新连接 if (!this.isManualClose) { this.close(); // 断开当前连接 this.connect(); // 重新连接 } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;使用示例:
import UniAppWebSocket from './UniAppWebSocket'; // 初始 token 可以在初始化时传入 const ws = new UniAppWebSocket('wss://example.com', { token: 'initial-token', enableHeartbeat: true, heartbeatInterval: 5000, reconnectInterval: 3000, maxReconnectAttempts: 5, enableQueue: true, debug: true, onOpen: () => console.log('WebSocket opened'), onMessage: (data) => console.log('Received:', data), onClose: () => console.log('WebSocket closed'), onError: (error) => console.log('WebSocket error:', error), }); // 手动进行连接 ws.connect(); // 发送消息 ws.sendMessage( { action: 'some_action', data: 'your_data_here' }, () => console.log('Message successfully sent!'), (error) => console.error('Message failed to send:', error), false // 处理队列中的消息重试时不调用回调 ); // 更新 token 并重新连接 ws.updateToken('new-token'); // 手动关闭连接 ws.close();设计要点:
- Token 更新:
updateToken方法用于更新 token,并触发连接的重置以确保新 token 被使用。 - 自定义 Headers:在连接时利用 headers 选项传递 token。
- 自动重连控制:在合适的条件下触发重新连接,确保 token 的变化被考虑在内。
如果有进一步要求或可能需要调整的地方,请随时告诉我!
- Token 更新:
- User
它是可选的
- Assistant
为了让使用
token进行身份验证成为可选功能,我们可以在初始化时将其视为一个可选参数。在没有指定 token 的情况下,我们只需正常建立 WebSocket 连接即可。以下是优化后的代码:class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.token = options.token || null; // 初始 token,默认为 null this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; // 初始化时不自动连接 } log(...args) { if (this.debug) { console.log(...args); } } connect() { if (this.isConnected() || this.reconnectTimer) { this.log('Already connected or attempting reconnect.'); return; } const headers = {}; if (this.token) { headers.Authorization = `Bearer ${this.token}`; // 使用 token 的自定义 header } this.isManualClose = false; // 准备进行连接或重连 this.webSocket = uni.connectSocket({ url: this.url, header: headers, // 设置 headers }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.currentReconnectAttempts = 0; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } } updateToken(newToken) { this.token = newToken; this.log('Token updated:', this.token); // 如有必要,更新 token 后重新连接 if (this.isConnected()) { this.close(); // 断开当前连接 this.connect(); // 重新连接 } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;说明:
- 可选 Token:
options.token默认为null,如果用户没有提供 token,则不会在头中添加 Authorization。 - 动态更新 Token:
updateToken方法允许在运行时更新 token,并在需要时重新连接。 - 动态 Headers 设置:在每次新连接时检查 token,确保仅在提供 token 时才添加授权头。
通过这种设计,应用可以灵活地选择是否以及何时使用 token 进行身份验证。如果有任何其他要求或想法,请随时告诉我!
- 可选 Token:
- User
方法名用setToken,而不是updateToken
- Assistant
当然,可以将方法名更改为
setToken来更好地符合命名约定。下面是更新后的代码:class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.token = options.token || null; // 初始 token,默认为 null this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; // 初始化时不自动连接 } log(...args) { if (this.debug) { console.log(...args); } } connect() { if (this.isConnected() || this.reconnectTimer) { this.log('Already connected or attempting reconnect.'); return; } const headers = {}; if (this.token) { headers.Authorization = `Bearer ${this.token}`; // 使用 token 的自定义 header } this.isManualClose = false; // 准备进行连接或重连 this.webSocket = uni.connectSocket({ url: this.url, header: headers, // 设置 headers }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Reconnecting... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.currentReconnectAttempts = 0; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } } setToken(newToken) { this.token = newToken; this.log('Token updated:', this.token); // 如有必要,更新 token 后重新连接 if (this.isConnected()) { this.close(); // 断开当前连接 this.connect(); // 重新连接 } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;说明:
setToken方法:用于设置或更新 token。如果 WebSocket 当前已连接,则会关闭并重新连接以应用新的 token。- 可选 Token 功能:仅当设置了 token 时才会在连接时使用 token 进行认证。
通过这样的调整,应用可以更灵活地控制身份验证逻辑。如果您有更多建议或问题,请随时告知!
- User
this.log('Token updated:', this.token); log的信息不是updated吧?
- Assistant
您是对的,日志消息应该清晰地表达方法的操作。
setToken方法的log信息可以更准确地描述它的功能,比如指出 token 已被设置或更改。以下是改进的日志信息:setToken(newToken) { this.token = newToken; this.log('Token set:', this.token); // 如有必要,更新 token 后重新连接 if (this.isConnected()) { this.close(); // 断开当前连接 this.connect(); // 重新连接 } }在上述代码中,我将日志信息从“Token updated”改为“Token set”,以反映
setToken方法的意图。这样可以让日志内容更精确。如果还有其他方面需要调整或优化,请随时告诉我!
- User
connect方法中 if (this.isConnected() || this.reconnectTimer) { this.log('Already connected or attempting reconnect.'); return; } -----如果连接失败,自动重连,根本不可能呀,自动重连 this.reconnectTimer肯定不为假
- Assistant
你提到的情况确实说明了一个潜在问题,连接失败时自动重连时
reconnectTimer不会立即为null。感谢你的指正。为此,我们需要仔细处理连接状态和重连逻辑,保证不会因为不必要的连接检查而阻止正常的重连或初次连接。以下是调整后的代码:
class UniAppWebSocket { constructor(url, options = {}) { this.url = url; this.token = options.token || null; this.heartbeatInterval = options.heartbeatInterval || 10000; this.reconnectInterval = options.reconnectInterval || 5000; this.maxReconnectAttempts = options.maxReconnectAttempts || 10; this.enableHeartbeat = options.enableHeartbeat !== false; this.enableQueue = options.enableQueue || false; this.debug = options.debug || false; this.currentReconnectAttempts = 0; this.isManualClose = false; this.heartbeatTimer = null; this.reconnectTimer = null; this.messageQueue = []; this.eventHandlers = { open: options.onOpen || (() => {}), message: options.onMessage || (() => {}), close: options.onClose || (() => {}), error: options.onError || (() => {}), }; } log(...args) { if (this.debug) { console.log(...args); } } connect() { if (this.isConnected()) { this.log('Already connected.'); return; } const headers = {}; if (this.token) { headers.Authorization = `Bearer ${this.token}`; } this.isManualClose = false; this.webSocket = uni.connectSocket({ url: this.url, header: headers }); this.webSocket.onOpen(() => this.handleOpen()); this.webSocket.onMessage((message) => this.handleMessage(message)); this.webSocket.onClose(() => this.handleClose()); this.webSocket.onError((error) => this.handleError(error)); } handleOpen() { this.log('WebSocket connected'); this.currentReconnectAttempts = 0; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } this.eventHandlers.open(); if (this.enableQueue) { this.processQueue(); } if (this.enableHeartbeat) { this.startHeartbeat(); } } handleMessage(message) { this.log('WebSocket message received:', message.data); const data = JSON.parse(message.data); this.eventHandlers.message(data); this.resetHeartbeat(); } handleClose() { this.log('WebSocket closed'); this.eventHandlers.close(); if (!this.isManualClose) { this.reconnect(); } } handleError(error) { this.log('WebSocket error:', error); this.eventHandlers.error(error); if (!this.isManualClose) { this.reconnect(); } } reconnect() { if (this.currentReconnectAttempts < this.maxReconnectAttempts) { this.currentReconnectAttempts++; this.log(`Attempting to reconnect... (Attempt ${this.currentReconnectAttempts})`); this.reconnectTimer = setTimeout(() => this.connect(), this.reconnectInterval); } else { this.log('Max reconnect attempts reached'); } } startHeartbeat() { this.clearHeartbeat(); this.heartbeatTimer = setInterval(() => { if (this.isConnected()) { this.sendMessage({ type: 'ping' }); } }, this.heartbeatInterval); } resetHeartbeat() { if (this.enableHeartbeat) { this.startHeartbeat(); } } clearHeartbeat() { if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = null; } } enqueueMessage(data, onSuccess, onError, callBackOnRetry) { this.messageQueue.push({ data, onSuccess, onError, callBackOnRetry }); } processQueue() { while (this.messageQueue.length > 0) { const { data, onSuccess, onError, callBackOnRetry } = this.messageQueue.shift(); this.sendMessage(data, callBackOnRetry ? onSuccess : null, callBackOnRetry ? onError : null); } } sendMessage(data, onSuccess, onError, callBackOnRetry = true) { if (this.isConnected()) { this.webSocket.send({ data: JSON.stringify(data), success: () => { this.log('Message sent successfully'); if (onSuccess) onSuccess(); }, fail: (error) => { this.log('Message send failed', error); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(error); }, }); } else { this.log('WebSocket is not open'); if (this.enableQueue) { this.enqueueMessage(data, onSuccess, onError, callBackOnRetry); } if (onError) onError(new Error('WebSocket is not open')); } } close() { this.isManualClose = true; this.currentReconnectAttempts = 0; this.clearHeartbeat(); if (this.webSocket) { this.webSocket.close(); } if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } } setToken(newToken) { this.token = newToken; this.log('Token set:', this.token); if (this.isConnected()) { this.close(); this.connect(); } } isConnected() { return this.webSocket && this.webSocket.readyState === 1; } } export default UniAppWebSocket;解释:
connect方法检查连接状态:现在只检查isConnected()以避免重复连接。- 自动重连:持续会在
handleError和handleClose中调用reconnect,只要没有手动关闭。 - 重连计时器:在
handleOpen成功连接时清除,防止误触发重复连接。
通过这些更改,饿代码结构应当更能令人信服地处理自动重连并确保不会因为重复调用
connect产生意外行为。再次感谢您对逻辑的详细检查,如果还有其他问题或需要进一步修改,请随时告诉我!