一、创建useWebSocket.js 文件
javascript
// useWebSocket.js
// 获取链接的URL前缀
import {
BASE_URL
} from "./request";
import {
ref,
onMounted,
onBeforeUnmount
} from "vue";
// 假设我们使用 uni-app 的 globalData 或 Vuex 来管理用户状态
// 这里为了简单起见,我们假设用户ID是直接从某处获取的
const useWebSocket = (
url,
reconnectInterval = 10000,
maxReconnectAttempts = 5
) => {
const isMounted = ref(true);
const isConnected = ref(false);
const messages = ref([]);
let reconnectAttempts = 0;
const connect = () => {
if (isConnected.value) {
uni.closeSocket(); // 关闭已有的 WebSocket 连接
}
const uri = `ws://${BASE_URL}/websocket/tender/${url}`;
// 使用微信小程序的 WebSocket API
uni.connectSocket({
url: uri,
success: () => {
console.log("WebSocket连接已打开");
isConnected.value = true;
// 监听消息
uni.onSocketMessage((res) => {
messages.value = JSON.parse(res.data);
});
// 监听WebSocket的关闭
uni.onSocketClose(() => {
console.log("WebSocket连接已关闭");
isConnected.value = false;
if (isMounted.value && reconnectAttempts < maxReconnectAttempts) {
setTimeout(connect, reconnectInterval * (reconnectAttempts + 1));
reconnectAttempts++;
}
});
// 监听WebSocket的错误
uni.onSocketError((res) => {
console.error("WebSocket发生错误:", res.errMsg);
if (isMounted.value) {
setTimeout(connect, reconnectInterval);
}
});
},
fail: (err) => {
console.error("WebSocket连接失败:", err);
}
});
};
const sendMessage = (message) => {
if (isConnected.value) {
uni.sendSocketMessage({
data: message,
success: () => {
console.log('消息发送成功');
},
fail: (err) => {
console.error('发送失败', err);
}
});
}
};
onMounted(() => {
isMounted.value = true;
connect();
});
onBeforeUnmount(() => {
isMounted.value = false;
if (isConnected.value) {
uni.closeSocket();
}
});
return {
isConnected,
messages,
sendMessage
};
};
export default useWebSocket;
二、在 .vue文件中使用
javascript
<script setup>
import {
onLoad
} from "@dcloudio/uni-app";
import {
ref,
watchEffect
} from 'vue';
// 引入useWebSocket
import useWebSocket from "@/api/useWebSocket.js";
onLoad((options) => {
id.value = options.id
messages.value = useWebSocket(options.id, 10000, 5);
})
// 监听messages
watchEffect(() => {
let timeVal = {
...messages.value
};
console.log(timeVal);
})
</script>