MAJOR FIX: Chat Latency Fixed

This commit is contained in:
Chris-1010
2025-01-29 17:41:40 +00:00
parent cf68d722b0
commit 6cfac0d78f
6 changed files with 124 additions and 76 deletions

View File

@@ -0,0 +1,57 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import { io, Socket } from 'socket.io-client';
interface SocketContextType {
socket: Socket | null;
isConnected: boolean;
}
const SocketContext = createContext<SocketContextType | undefined>(undefined);
export const SocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [socket, setSocket] = useState<Socket | null>(null);
const [isConnected, setIsConnected] = useState(false);
useEffect(() => {
const newSocket = io("http://localhost:8080", {
path: "/socket.io/",
withCredentials: true,
transports: ['websocket'],
upgrade: false
});
newSocket.on('connect', () => {
console.log('Socket connected!');
setIsConnected(true);
});
newSocket.on('connect_error', (error) => {
console.error('Socket connection error:', error);
});
newSocket.on('disconnect', () => {
console.log('Socket disconnected!');
setIsConnected(false);
});
setSocket(newSocket);
return () => {
newSocket.close();
};
}, []);
return (
<SocketContext.Provider value={{ socket, isConnected }}>
{children}
</SocketContext.Provider>
);
};
export const useSocket = () => {
const context = useContext(SocketContext);
if (context === undefined) {
throw new Error('useSocket must be used within a SocketProvider');
}
return context;
};