Skip to content

Commit

Permalink
refactor: update WebSocket connection handling and improve logging
Browse files Browse the repository at this point in the history
- Modified useWebSocket hook to enhance connection logging and removed redundant connection checks.
- Updated server.ts to improve startup logging messages for better clarity on server status.
- Changed docker-compose.yml to use quotes for port mapping for consistency.
  • Loading branch information
kiritoko1029 committed Dec 23, 2024
1 parent 7cd811c commit 38b42d1
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 31 deletions.
29 changes: 6 additions & 23 deletions app/hooks/useWebSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,17 @@ export function useWebSocket() {
const setOnlineUsers = useWebSocketStore((state) => state.setOnlineUsers);

const setupWebSocket = useCallback(() => {
// 如果已经有连接或正在重连,不要创建新连接
if (
wsRef.current?.readyState === WebSocket.OPEN ||
wsRef.current?.readyState === WebSocket.CONNECTING
) {
return;
}

// 清理现有连接
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}

// 清理重连定时器
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}

try {
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(`${protocol}//${window.location.host}/ws`);
const host = window.location.host;
console.log(`Connecting to WebSocket at ${protocol}//${host}/ws`);

const ws = new WebSocket(`${protocol}//${host}/ws`);
wsRef.current = ws;

ws.onopen = () => {
console.log("WebSocket connected");
reconnectAttemptsRef.current = 0; // 重置重连次数
console.log("WebSocket connected successfully");
reconnectAttemptsRef.current = 0;
ws.send(JSON.stringify({ type: "getOnline" }));
};

Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ services:
container_name: chatgpt-next-web
image: yidadaa/chatgpt-next-web
ports:
- 3000:3000
- "3000:3000"
environment:
- OPENAI_API_KEY=$OPENAI_API_KEY
- GOOGLE_API_KEY=$GOOGLE_API_KEY
Expand Down
9 changes: 2 additions & 7 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,6 @@ const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = createServer(async (req, res) => {
try {
if (req.url === '/ws') {
res.writeHead(400);
res.end();
return;
}

const parsedUrl = parse(req.url!, true);
await handle(req, res, parsedUrl);
} catch (err) {
Expand All @@ -31,6 +25,7 @@ app.prepare().then(() => {
setupWebSocket(server);

server.listen(port, hostname, () => {
console.log(`> Ready on http://${hostname}:${port}`);
console.log(`> Server listening at http://${hostname}:${port}`);
console.log(`> WebSocket server is ready`);
});
});

0 comments on commit 38b42d1

Please sign in to comment.