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 TextDe
07-13
1516
09-10
2520