【Uniapp】封装websocket
该文件中中没有进行心跳监测,直接使用的uniapp的链接错误回调
·
1、封装websocket
创建websocket.js文件,文件内容如下
class Ws{
//初始化
constructor() {
//ws地址
this.wsUrl = 'ws://' + '自己的地址';
//websocket对象
this.socketTask = null;
this.state = false
//是否人为关闭
this.isPeopleClose = false;
//断线重连机制
this.reconnectInterval = null;
//重连时间
this.reconnectTimeOut = 5000;
//重连次数
this.reconnectCount = 10;
// 断网重连
uni.onNetworkStatusChange((res) => {
if (res.isConnected) {
this.connect();
}
});
}
//单例模式可参考链接 https://www.runoob.com/design-pattern/singleton-pattern.html
static getInstance() {
if (!this.instance) {
this.instance = new Chat();
}
return this.instance;
}
//建立连接
connect() {
try {
let that = this
this.socketTask = uni.connectSocket({
url: this.wsUrl,
success: () => {
console.log("正在建立连接");
return this.socketTask
},
fail: (err) => {
this.reconnect();
},
});
//打开连接正常
this.socketTask.onOpen(async (res) => {
console.log(this.wsUrl)
console.log("打开连接成功");
//清除断开重连定时器,
clearInterval(this.reconnectInterval);
this.state = false
//设置重连次数
this.reconnectCount = 10;
//重置人为关闭状态
this.isPeopleClose = false;
//监听接收消息
this.socketTask.onMessage((res) => {
console.log('接收到数据')
// 可以针对自己的实际业务对返回的数据进行处理
});
})
// 检测到发生异常时的回调方法
this.socketTask.onError((err) => {
console.error('onError',this.state);
if(this.state == false){
//重连
this.reconnect();
}
})
this.socketTask.onClose(() => {
console.log('onClose');
//重连
this.reconnect();
})
} catch (e) {
//重连
this.reconnect();
}
}
//手动关闭连接
close() {
console.log('close');
this.isPeopleClose = true;
this.socketTask.close({
success(res) {
console.log("关闭成功")
},
fail(err) {
}
})
}
//断线重连
reconnect() {
//非人为关闭则尝试重连
console.log('进行断线重连');
if (!this.isPeopleClose) {
this.state = true
this.reconnectInterval = setInterval(() => {
//如果重连次数小于0则清除定时器
if (this.reconnectCount > 0) {
console.log('正在重连,第' + this.reconnectCount + '次');
this.connect();
this.reconnectCount--;
} else {
clearInterval(this.reconnectInterval);
let that = this
uni.showModal({
title: '提示',
cancelText: '继续连接',
confirmText: '确定',
showCancel:true,
content: '断开连接,请检查网络!',
success: function(res) {
if (res.cancel) {
that.reconnectCount = 10;
that.reconnect();
} else if (res.confirm) {
console.log('用户点击取消');
}
}
});
}
}, this.reconnectTimeOut);
}
}
}
export default Ws;
2、页面中使用
import Ws from "../../untils/websocket.js"; //在需要使用的页面中引用上述js文件
Ws .getInstance().connect() // 连接websocket
更多推荐
已为社区贡献4条内容
所有评论(0)