This commit is contained in:
魏啾
2024-06-07 17:21:52 +08:00
parent c8633827cc
commit 5a16a5199e
2 changed files with 166 additions and 192 deletions

View File

@@ -1,148 +1,146 @@
class webSocketUtils {
constructor(url, time, params) {
this.socketTask = null;
this.is_open_socket = false; //避免重复连接
this.url = url;
this.params = params ? params : null;////是否初始化请求
this.connectNum = 1; // 重连次数
//这个参数是防止重连失败之后onClose方法会重复执行reconnect方法导致重连定时器出问题
//连接并打开之后可重连,且只执行重连方法一次
this.canReconnect = false; // 是否可以重连
//心跳检测
this.timeout = time ? time : 5000; //多少秒执行检测
this.heartbeatInterval = null; //检测服务器端是否还活着
this.reconnectTimeOut = null; //重连之后多久再次重连
try {
return this.connectSocketInit({
data: this.params,
type: 'connectSocketInit',
});
} catch (e) {
console.log('catch');
this.reconnect();
}
}
// 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit (data) {
console.log(data,"初始化")
this.data = data;
console.log('this.url==', this.url);
this.socketTask = uni.connectSocket({
url: this.url,
success: () => {
console.log('正准备建立websocket中...');
// uni.hideLoading();
// 返回实例
return this.socketTask;
},
});
console.log('this.params==', this.params);
this.socketTask.onOpen((res) => {
this.connectNum = 1;
console.log('WebSocket连接正常');
if(this.params){//是否初始化请求
this.send(this.params);
}
clearInterval(this.reconnectTimeOut);
clearInterval(this.heartbeatInterval);
this.is_open_socket = true;
this.canReconnect = true;
this.start();
// 注:只有连接正常打开中 ,才能正常收到消息
this.socketTask.onMessage((e) => {
// 字符串转json
let res = JSON.parse(e.data);
uni.$emit('message', res)
// 普通socket信息处理 TODO
});
});
// 监听连接失败这里代码我注释掉的原因是因为如果服务器关闭后和下面的onclose方法一起发起重连操作这样会导致重复连接
uni.onSocketError((res) => {
console.log('网络断开,请检查!');
this.socketTask = null;
this.is_open_socket = false;
this.canReconnect = true;
clearInterval(this.heartbeatInterval);
clearInterval(this.reconnectTimeOut);
if (this.connectNum <= 10) {
uni.showToast({
title: `网络连接失败,正尝试第${this.connectNum}次连接`,
icon: 'none',
});
this.reconnect();
this.connectNum += 1;
} else {
// uni.$emit('connectError');
uni.showToast({
title: `网络连接失败,请检查网络!`,
icon: 'none',
});
this.connectNum = 1;
this.canReconnect = false;
}
});
// 这里仅是事件监听【如果socket关闭了会执行】
this.socketTask.onClose(() => {
this.socketTask = null;
clearInterval(this.heartbeatInterval);
clearInterval(this.reconnectTimeOut);
this.is_open_socket = false;
if (this.canReconnect) {
this.reconnect();
this.canReconnect = false;
}
});
}
// 主动关闭socket连接
Close () {
this.is_open_socket = true;
this.canReconnect = false;
if(this.socketTask){
this.socketTask.close({
success(res) {
console.log('手动关闭成功');
},
});
}
}
//发送消息
send(data) {
console.log("发送消息---------->", data);
// 注:只有连接正常打开中 ,才能正常成功发送消息
if (this.socketTask) {
this.socketTask.send({
data: JSON.stringify(data),
async success() {
console.log("消息发送成功");
},
});
}
}
//开启心跳检测
start(data) {
console.log('开启心跳检测',data)
this.heartbeatInterval = setInterval(() => {
this.send({
data: '心跳检测',
type: 'heartbeat',
});
}, this.timeout);
}
//重新连接
reconnect() {
//停止发送心跳
clearInterval(this.heartbeatInterval);
//如果不是人为关闭的话,进行重连
if (!this.is_open_socket) {
console.log('进行重连');
// this.canReconnect = true;
this.reconnectTimeOut = setInterval(() => {
this.connectSocketInit(this.data);
}, this.timeout);
}
}
constructor(url, time, params) {
this.socketTask = null;
this.is_open_socket = false; //避免重复连接
this.url = url;
this.params = params ? params : null; ////是否初始化请求
this.connectNum = 1; // 重连次数
//这个参数是防止重连失败之后onClose方法会重复执行reconnect方法导致重连定时器出问题
//连接并打开之后可重连,且只执行重连方法一次
this.canReconnect = false; // 是否可以重连
//心跳检测
this.timeout = time ? time : 5000; //多少秒执行检测
this.heartbeatInterval = null; //检测服务器端是否还活着
this.reconnectTimeOut = null; //重连之后多久再次重连
try {
return this.connectSocketInit({
data: this.params,
type: 'connectSocketInit',
});
} catch (e) {
console.log('catch');
this.reconnect();
}
}
// 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit(data) {
this.data = data;
this.socketTask ? this.socketTask.Close() : null
this.socketTask = uni.connectSocket({
url: this.url,
success: () => {
console.log('正准备建立websocket中...');
// uni.hideLoading();
// 返回实例
return this.socketTask;
},
});
this.socketTask.onOpen((res) => {
this.connectNum = 1;
console.log('WebSocket连接正常');
if (this.params) { //是否初始化请求
this.send(this.params);
}
clearInterval(this.reconnectTimeOut);
clearInterval(this.heartbeatInterval);
this.is_open_socket = true;
this.canReconnect = true;
this.start();
// 注:只有连接正常打开中 ,才能正常收到消息
this.socketTask.onMessage((e) => {
// 字符串转json
let res = JSON.parse(e.data);
uni.$emit('message', res)
// 普通socket信息处理 TODO
});
});
// 监听连接失败这里代码我注释掉的原因是因为如果服务器关闭后和下面的onclose方法一起发起重连操作这样会导致重复连接
uni.onSocketError((res) => {
console.log('网络断开,请检查!');
this.socketTask = null;
this.is_open_socket = false;
this.canReconnect = true;
clearInterval(this.heartbeatInterval);
clearInterval(this.reconnectTimeOut);
if (this.connectNum <= 10) {
uni.showToast({
title: `网络连接失败,正尝试第${this.connectNum}次连接`,
icon: 'none',
});
this.reconnect();
this.connectNum += 1;
} else {
// uni.$emit('connectError');
uni.showToast({
title: `网络连接失败,请检查网络!`,
icon: 'none',
});
this.connectNum = 1;
this.canReconnect = false;
}
});
// 这里仅是事件监听【如果socket关闭了会执行】
this.socketTask.onClose(() => {
this.socketTask = null;
clearInterval(this.heartbeatInterval);
clearInterval(this.reconnectTimeOut);
this.is_open_socket = false;
if (this.canReconnect) {
this.reconnect();
this.canReconnect = false;
}
});
}
// 主动关闭socket连接
Close() {
this.is_open_socket = true;
this.canReconnect = false;
if (this.socketTask) {
this.socketTask.close({
success(res) {
console.log('手动关闭成功');
},
});
}
}
//发送消息
send(data) {
console.log("发送消息---------->", data);
// 注:只有连接正常打开中 ,才能正常成功发送消息
if (this.socketTask) {
this.socketTask.send({
data: JSON.stringify(data),
async success() {
console.log("消息发送成功");
},
});
}
}
//开启心跳检测
start(data) {
console.log('开启心跳检测', data)
this.heartbeatInterval = setInterval(() => {
this.send({
data: '心跳检测',
type: 'heartbeat',
});
}, this.timeout);
}
//重新连接
reconnect() {
//停止发送心跳
clearInterval(this.heartbeatInterval);
//如果不是人为关闭的话,进行重连
if (!this.is_open_socket) {
console.log('进行重连');
this.canReconnect = true;
this.reconnectTimeOut = setInterval(() => {
this.connectSocketInit(this.data);
}, this.timeout);
}
}
}
module.exports = webSocketUtils;

View File

@@ -283,42 +283,32 @@
uni.reLaunch({
url: '/pages/login/login?types=' + 0
});
return false
}
uni.$on('message', this.getMessage)
setTimeout(() => {
if (uni.cache.get('token') && uni.cache.get('tableCode')) {
this.productqueryShopIdByTableCode() //获取shop User id
}
}, 500)
this.$nextTick(() => {
this.countTitleTopNum(); //导航栏
});
},
onUnload() {
this.socketSendMsg({ //定义socket数据传参
"type": "close", //“addcart:添加购物车create0rder:生成订单clearCart:庆康购物车”,
})
console.log(this.socketTicket, '关闭长连接')
try {
this.socketSendMsg({ //定义socket数据传参
"type": "close", //“addcart:添加购物车create0rder:生成订单clearCart:庆康购物车”,
})
} catch (e) {
//TODO handle the exception
}
this.socketTicket.Close()
uni.$off('message')
},
onShow() {
// console.log(this.socketTicket,'进入页面')
// if (this.socketTicket) {
// this.socketTicket.Close()
// uni.$off('message')
// }
// uni.onNetworkStatusChange((res) => { //监听网络状态变化
// if (!res.isConnected) {
// // 检查网络是否连接
// } else {
// console.log(res, 111);
// // ...这里写你的业务逻辑
// }
// });
// setTimeout()
this.handlemessage()
setTimeout(() => {
console.log('调试1')
if (uni.cache.get('token') && uni.cache.get('tableCode')) {
this.productqueryShopIdByTableCode() //获取shop User id
}
}, 500)
},
methods: {
// 单独获取他的shopUserid
@@ -337,16 +327,6 @@
uni.pro.switchTab('index/index')
}, 1000)
}
// try {
// if (res.data) {
// let time = new Date
// console.log(time, '时间戳')
// uni.cache.set('shopUser', res.data)
// this.handlemessage()
// }
// } catch (e) {
// //TODO handle the exception
// }
},
getMessage(msg) { //wss 回显数据
if (msg.status != 'success') {
@@ -432,17 +412,12 @@
},
handlemessage() {
this.socketTicket ? this.socketTicket.Close() : null //调用前先判断是否有socket正在进行 先关闭后链接
// this.socketTicket = new webSocketUtils(
// `${uni.conf.baseUrlwws}/websocket/table?tableId=${uni.cache.get('tableCode')}&shopId=${uni.cache.get('shopUser')}&userId=${uni.cache.get('userInfo').id}`,
// 5000)
this.socketTicket = new webSocketUtils(
`${uni.conf.baseUrlwws}`,
5000, {
tableId: uni.cache.get('tableCode'),
shopId: uni.cache.get('shopUser'),
userId: uni.cache.get('userInfo').id,
"type": "connect",
})
this.socketTicket = new webSocketUtils(`${uni.conf.baseUrlwws}`, 5000, {
tableId: uni.cache.get('tableCode'),
shopId: uni.cache.get('shopUser'),
userId: uni.cache.get('userInfo').id,
"type": "connect",
})
},
// 数据处理
socketSendMsg(data) {
@@ -499,7 +474,7 @@
},
async cartadd(item, index, index1, a, b, guge) { //列表添加
console.log(item, index, index1, a, b, guge)
if (guge == '单规格') { //没有规格为空
this.specifications.duoguge = ''
this.skuidname = []
@@ -665,6 +640,7 @@
switch (t) {
case 1:
// 返回
this.socketTicket.Close()
uni.switchTab({
url: '/pages/index/index'
})