修改websocket为全局只有一个

This commit is contained in:
2025-05-19 09:07:35 +08:00
parent ac28ee855f
commit c7e4e5e26b
8 changed files with 3780 additions and 269 deletions

View File

@@ -31,8 +31,7 @@ const useWebSocket = (options = {}) => {
const allowReconnect = ref(true); // 新增:控制是否允许重连
// 关闭现有连接并清理资源
const closeExistingConnection = () => {
if (socketTask.value) {
// 关闭 WebSocket 连接
try {
socketTask.value.close({
success: () => {
console.log('WebSocket 连接已关闭');
@@ -52,13 +51,32 @@ const useWebSocket = (options = {}) => {
// 标记连接已断开
isConnected.value = false;
} catch (error) {
console.error(error)
//TODO handle the exception
}
};
const websocketsendMessage = (data) => {
uni.$u.debounce(sendMessage(data), 500)
}
const safeConnect=(connectMsg)=>{
return new Promise((resolve,reject)=>{
try {
sendMessage(connectMsg ? connectMsg : initMessage)
resolve(true)
} catch (error) {
reject(false)
//TODO handle the exception
}
})
}
// 连接 WebSocket
const connect = (connectMsg) => {
const connect =async (connectMsg) => {
if (!isNetworkConnected.value) {
uni.showToast({
title: '网络未连接...',
@@ -72,13 +90,14 @@ const useWebSocket = (options = {}) => {
}
// 关闭现有连接并清理资源
try{
closeExistingConnection();
}catch(err){
const sendSuccess= await safeConnect(connectMsg)
if(sendSuccess){
return
}else{
closeExistingConnection()
}
socketTask.value = uni.connectSocket({
url: uni.conf.baseUrlwws,
url: uni.conf.baseUrlwws + '?' + Date.now(),
success: (res) => {
isConnected.value = true;
// 监听初始化成功在开启心跳
@@ -228,6 +247,7 @@ const useWebSocket = (options = {}) => {
// 手动关闭连接
const closeSocket = () => {
console.log('手动关闭连接');
isManuallyClosed.value = true;
closeExistingConnection();
};
@@ -345,7 +365,7 @@ const useWebSocket = (options = {}) => {
}
onBeforeUnmount(() => {
closeSocket();
// closeSocket();
});
return {
@@ -357,7 +377,8 @@ const useWebSocket = (options = {}) => {
connect,
onShowconnect,
initNetworkListener,
connect,allowReconnect
connect,
allowReconnect
};
};