欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > uni-app 封装websocket 心跳检测,开箱即用

uni-app 封装websocket 心跳检测,开箱即用

2025/2/23 7:08:11 来源:https://blog.csdn.net/cyj0919/article/details/142590029  浏览:    关键词:uni-app 封装websocket 心跳检测,开箱即用
class websocketUtils {constructor(url, needbeat, options = {}) {this.needbeat = needbeat;this.url = url;this.options = options;this.ws = null;this.heartbeatInterval = options.heartbeatInterval || 10000; // 心跳间隔,默认为10秒  this.reconnectInterval = options.reconnectInterval || 5000; // 重连间隔,默认为5秒  this.reconnectAttempts = options.reconnectAttempts || Infinity; // 最大重连次数,默认为无限次  this.reconnectCount = 0;this.initWebSocket();}initWebSocket() {this.ws = uni.connectSocket({url: this.url,success: () => {console.log('WebSocket连接成功');if (this.needbeat) {this.startHeartbeat();}this.onOpen();},fail: (err) => {console.error('WebSocket连接失败', err);this.reconnect();}});// 监听WebSocket接收到服务器的消息事件  this.ws.onMessage((result) => {// const textDecoder = new TextDecoder();// let text = textDecoder.decode(result.data)// console.log('自定义处理消息:',result);this.onMessage(result);// 收到消息后,可能需要重置心跳计时器  // 是否需要心跳选择器if (this.needbeat) {this.resetHeartbeat();}})// 监听WebSocket关闭事件  this.ws.onClose(res => {console.log('WebSocket连接已关闭', res);this.onClose();this.reconnect();});// 监听WebSocket错误事件  this.ws.onError(err => {console.error('WebSocket发生错误', err);this.onError(err);this.reconnect();});}// 发送消息  send(data) {if (this.ws) {this.ws.send({data: data,success: () => {console.log('消息发送成功');},fail: (err) => {console.error('消息发送失败', err);}})}}// 心跳检测  startHeartbeat() {this.heartbeatTimer = setInterval(() => {this.sendHeartbeat();}, this.heartbeatInterval);}// 重置心跳计时器  resetHeartbeat() {clearInterval(this.heartbeatTimer);this.startHeartbeat();}// 发送心跳消息  sendHeartbeat() {this.send('ping'); // 假设心跳消息为'ping'  }// 重连逻辑  reconnect() {if (this.reconnectCount < this.reconnectAttempts) {setTimeout(() => {this.initWebSocket();this.reconnectCount++;}, this.reconnectInterval);}}// 自定义事件处理  onOpen() {}onMessage(data) {}onClose() {}onError(err) {}// 关闭WebSocket连接  close() {if (this.ws) {this.ws.close({success: () => {console.log('WebSocket连接已关闭');},fail: (err) => {console.error("wss关闭失败->", err)}});clearInterval(this.heartbeatTimer);this.ws = null;}}
}
export default websocketUtils;

使用

let socket = new websocketUtils(wss_.url, false, {heartbeatInterval: 5000,reconnectInterval: 3000,reconnectAttempts: 5
});socket.onMessage = function(evt) {//获取消息
};socket.send(message);//发送消息
socket.close();//关闭sockett

版权声明:

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

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

热搜词