websocket优化

This commit is contained in:
kron
2025-06-22 02:39:03 +08:00
parent 322f23efb4
commit d075844cb0
6 changed files with 50 additions and 22 deletions

View File

@@ -1,11 +1,12 @@
<script setup>
import { watch } from "vue";
import { watch, onMounted, onUnmounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import websocket from "@/websocket";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);
const { updateConnect } = store;
const { updateConnect, updateUser } = store;
watch(
() => user.value.id,
@@ -16,12 +17,32 @@ watch(
uni.$emit("socket-inbox", content);
});
}
if (!newVal) {
updateConnect(false);
websocket.closeWebSocket();
}
},
{
deep: false, // 如果 user 是一个对象或数组,建议开启
immediate: false, // 若想在初始化时立即执行一次回调,可开启。
}
);
onShow(() => {
const token = uni.getStorageSync("token");
if (user.value.id && token) {
// 检查 WebSocket 连接状态
uni.sendSocketMessage({
data: JSON.stringify({ event: "ping", data: {} }),
fail: () => {
// 如果发送失败,说明连接已断开,需要重新连接
websocket.createWebSocket(token, updateConnect, (content) => {
uni.$emit("socket-inbox", content);
});
},
});
}
});
</script>
<style>

View File

@@ -13,6 +13,9 @@ function request(method, url, data = {}) {
success: (res) => {
if (res.data.code === 0) resolve(res.data.data);
else {
if (res.data.message.indexOf("登录身份已失效") !== -1) {
uni.removeStorageSync("token");
}
uni.showToast({
title: res.data.message,
icon: "none",

View File

@@ -18,7 +18,7 @@ const tabs = [
];
function handleTabClick(index) {
if (!user.value.id) return props.signin();
if (index !== 2 && !user.value.id) return props.signin();
if (index === 0) {
uni.navigateTo({
url: "/pages/be-vip",

View File

@@ -11,7 +11,7 @@ import { storeToRefs } from "pinia";
const store = useStore();
const { updateConfig, updateUser, updateDevice } = store;
// 使用storeToRefs用于UI里显示保持响应性
const { user, device } = storeToRefs(store);
const { user, device, remoteConnect } = storeToRefs(store);
const showModal = ref(false);
const isIos = ref(true);
@@ -48,18 +48,21 @@ onMounted(async () => {
const config = await getAppConfig();
console.log("全局配置:", config);
updateConfig(config);
const result = await getHomeData();
if (result.user) {
updateUser(result.user);
const devices = await getMyDevicesAPI();
if (devices.bindings && devices.bindings.length) {
updateDevice(
devices.bindings[0].deviceId,
devices.bindings[0].deviceName
);
const token = uni.getStorageSync("token");
if (token) {
const result = await getHomeData();
if (result.user) {
updateUser(result.user);
const devices = await getMyDevicesAPI();
if (devices.bindings && devices.bindings.length) {
updateDevice(
devices.bindings[0].deviceId,
devices.bindings[0].deviceName
);
}
}
console.log("首页数据:", result);
}
console.log("首页数据:", result);
} catch (error) {
console.error("获取配置失败:", error);
}
@@ -129,7 +132,7 @@ onMounted(async () => {
<image src="../static/avatar.png" mode="aspectFill" />
</view>
<view class="more-players" @click.stop="toRankListPage"
><text>4563</text></view
><text>456{{ remoteConnect ? 1 : 0 }}</text></view
>
</view>
</view>

View File

@@ -33,7 +33,7 @@ export default defineStore("store", {
updateConnect(connect) {
this.remoteConnect = connect;
},
updateUser(user) {
updateUser(user = {}) {
this.user = { ...defaultUser, ...user };
const rankInfos = this.config.randInfos || [];
let lvlName = "";

View File

@@ -40,7 +40,7 @@ function createWebSocket(token, onUpdate, onMessage) {
console.log("WebSocket 已关闭", result);
onUpdate(false);
stopHeartbeat();
reconnect(token, onMessage);
reconnect(onMessage);
});
// 启动心跳
@@ -50,17 +50,18 @@ function createWebSocket(token, onUpdate, onMessage) {
/**
* 重连机制
*/
function reconnect(token, onMessage) {
function reconnect(onMessage) {
if (reconnectCount >= RECONNECT_CONFIG.MAX_COUNT) return;
reconnectTimer && clearTimeout(reconnectTimer);
const token = uni.getStorageSync("token");
if (!token) return;
// 计算重连延迟(指数退避)
const delay = Math.min(
RECONNECT_CONFIG.INITIAL_DELAY * Math.pow(2, reconnectCount),
RECONNECT_CONFIG.MAX_DELAY
);
reconnectTimer = setTimeout(() => {
console.log("reconnecting...");
createWebSocket(token, onMessage);
@@ -70,11 +71,11 @@ function reconnect(token, onMessage) {
function closeWebSocket() {
if (socket) {
socket.close();
stopHeartbeat();
// 清理重连定时器
reconnectTimer && clearTimeout(reconnectTimer);
reconnectCount = 0;
reconnectTimer && clearTimeout(reconnectTimer);
stopHeartbeat();
socket.close();
}
}