fix: infinite retry when websocket error

This commit is contained in:
GyDi 2023-03-16 17:03:00 +08:00
parent c77db23586
commit db99b4cb54
No known key found for this signature in database
GPG Key ID: 9C3AD40F1F99880A
4 changed files with 95 additions and 65 deletions

View File

@ -5,6 +5,7 @@ import { useClashInfo } from "@/hooks/use-clash";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { TrafficGraph, type TrafficRef } from "./traffic-graph"; import { TrafficGraph, type TrafficRef } from "./traffic-graph";
import { useLogSetup } from "./use-log-setup"; import { useLogSetup } from "./use-log-setup";
import { useWebsocket } from "@/hooks/use-websocket";
import parseTraffic from "@/utils/parse-traffic"; import parseTraffic from "@/utils/parse-traffic";
// setup the traffic // setup the traffic
@ -18,58 +19,36 @@ const LayoutTraffic = () => {
const trafficRef = useRef<TrafficRef>(null); const trafficRef = useRef<TrafficRef>(null);
const [traffic, setTraffic] = useState({ up: 0, down: 0 }); const [traffic, setTraffic] = useState({ up: 0, down: 0 });
const wsRef = useRef<WebSocket | null>(null);
const [refresh, setRefresh] = useState({});
// setup log ws during layout // setup log ws during layout
useLogSetup(); useLogSetup();
useEffect(() => { const { connect, disconnect } = useWebsocket((event) => {
if (!clashInfo) return;
const { server = "", secret = "" } = clashInfo;
const ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ITrafficItem; const data = JSON.parse(event.data) as ITrafficItem;
trafficRef.current?.appendData(data); trafficRef.current?.appendData(data);
setTraffic(data); setTraffic(data);
}); });
ws.addEventListener("error", () => { useEffect(() => {
setTimeout(() => { if (!clashInfo) return;
if (document.visibilityState === "visible") {
setRefresh({});
}
}, 1000);
});
ws.addEventListener("close", () => { const { server = "", secret = "" } = clashInfo;
setTimeout(() => { connect(`ws://${server}/traffic?token=${secret}`);
if (document.visibilityState === "visible") {
setRefresh({});
}
}, 1000);
});
wsRef.current = ws;
return () => { return () => {
ws?.close(); disconnect();
wsRef.current = null;
}; };
}, [clashInfo, refresh]); }, [clashInfo]);
useEffect(() => { useEffect(() => {
// 页面隐藏时去掉请求
const handleVisibleChange = () => { const handleVisibleChange = () => {
if (!clashInfo) return;
if (document.visibilityState === "visible") { if (document.visibilityState === "visible") {
// reconnect websocket // reconnect websocket
if ( const { server = "", secret = "" } = clashInfo;
wsRef.current && connect(`ws://${server}/traffic?token=${secret}`);
wsRef.current.readyState !== WebSocket.CONNECTING } else {
) { disconnect();
setRefresh({});
}
} }
}; };

View File

@ -1,9 +1,10 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useEffect, useState } from "react"; import { useEffect } from "react";
import { useRecoilValue, useSetRecoilState } from "recoil"; import { useRecoilValue, useSetRecoilState } from "recoil";
import { getClashLogs } from "@/services/cmds"; import { getClashLogs } from "@/services/cmds";
import { useClashInfo } from "@/hooks/use-clash"; import { useClashInfo } from "@/hooks/use-clash";
import { atomEnableLog, atomLogData } from "@/services/states"; import { atomEnableLog, atomLogData } from "@/services/states";
import { useWebsocket } from "@/hooks/use-websocket";
const MAX_LOG_NUM = 1000; const MAX_LOG_NUM = 1000;
@ -14,17 +15,7 @@ export const useLogSetup = () => {
const enableLog = useRecoilValue(atomEnableLog); const enableLog = useRecoilValue(atomEnableLog);
const setLogData = useSetRecoilState(atomLogData); const setLogData = useSetRecoilState(atomLogData);
const [refresh, setRefresh] = useState({}); const { connect, disconnect } = useWebsocket((event) => {
useEffect(() => {
if (!enableLog || !clashInfo) return;
getClashLogs().then(setLogData);
const { server = "", secret = "" } = clashInfo;
const ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ILogItem; const data = JSON.parse(event.data) as ILogItem;
const time = dayjs().format("MM-DD HH:mm:ss"); const time = dayjs().format("MM-DD HH:mm:ss");
setLogData((l) => { setLogData((l) => {
@ -33,10 +24,16 @@ export const useLogSetup = () => {
}); });
}); });
ws.addEventListener("error", () => { useEffect(() => {
setTimeout(() => setRefresh({}), 1000); if (!enableLog || !clashInfo) return;
});
return () => ws?.close(); getClashLogs().then(setLogData);
}, [clashInfo, enableLog, refresh]);
const { server = "", secret = "" } = clashInfo;
connect(`ws://${server}/logs?token=${secret}`);
return () => {
disconnect();
};
}, [clashInfo, enableLog]);
}; };

View File

@ -0,0 +1,49 @@
import { useRef } from "react";
export type WsMsgFn = (event: MessageEvent<any>) => void;
interface Options {
errorCount?: number; // default is 5
retryInterval?: number; // default is 2500
}
export const useWebsocket = (onMessage: WsMsgFn, options?: Options) => {
const wsRef = useRef<WebSocket | null>(null);
const timerRef = useRef<any>(null);
const disconnect = () => {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};
const connect = (url: string) => {
let errorCount = options?.errorCount ?? 5;
if (!url) return;
const connectHelper = () => {
disconnect();
const ws = new WebSocket(url);
wsRef.current = ws;
ws.addEventListener("message", onMessage);
ws.addEventListener("error", () => {
errorCount -= 1;
if (errorCount >= 0) {
timerRef.current = setTimeout(connectHelper, 2500);
}
});
};
connectHelper();
};
return { connect, disconnect };
};

View File

@ -17,6 +17,7 @@ import { closeAllConnections } from "@/services/api";
import { atomConnectionSetting } from "@/services/states"; import { atomConnectionSetting } from "@/services/states";
import { useClashInfo } from "@/hooks/use-clash"; import { useClashInfo } from "@/hooks/use-clash";
import { BaseEmpty, BasePage } from "@/components/base"; import { BaseEmpty, BasePage } from "@/components/base";
import { useWebsocket } from "@/hooks/use-websocket";
import ConnectionItem from "@/components/connection/connection-item"; import ConnectionItem from "@/components/connection/connection-item";
import ConnectionTable from "@/components/connection/connection-table"; import ConnectionTable from "@/components/connection/connection-table";
@ -53,15 +54,9 @@ const ConnectionsPage = () => {
return connections; return connections;
}, [connData, filterText, curOrderOpt]); }, [connData, filterText, curOrderOpt]);
useEffect(() => { const { connect, disconnect } = useWebsocket(
if (!clashInfo) return; (event) => {
const { server = "", secret = "" } = clashInfo;
const ws = new WebSocket(`ws://${server}/connections?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as IConnections; const data = JSON.parse(event.data) as IConnections;
// 尽量与前一次connections的展示顺序保持一致 // 尽量与前一次connections的展示顺序保持一致
setConnData((old) => { setConnData((old) => {
const oldConn = old.connections; const oldConn = old.connections;
@ -93,9 +88,19 @@ const ConnectionsPage = () => {
return { ...data, connections }; return { ...data, connections };
}); });
}); },
{ errorCount: 3, retryInterval: 1000 }
);
return () => ws?.close(); useEffect(() => {
if (!clashInfo) return;
const { server = "", secret = "" } = clashInfo;
connect(`ws://${server}/connections?token=${secret}`);
return () => {
disconnect();
};
}, [clashInfo]); }, [clashInfo]);
const onCloseAll = useLockFn(closeAllConnections); const onCloseAll = useLockFn(closeAllConnections);