generated from Blazity/next-enterprise
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
610ff9c
commit 348160a
Showing
7 changed files
with
38,766 additions
and
2,517 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
// context/WebSocketContext.tsx | ||
import { createContext, ReactNode, useContext, useEffect, useState } from 'react'; | ||
|
||
type WebSocketContextType = { | ||
messages: string[]; | ||
sendMessage: (message: string) => void; | ||
connectionStatus: string; | ||
}; | ||
|
||
const WebSocketContext = createContext<WebSocketContextType | undefined>(undefined); | ||
|
||
export function useWebSocket() { | ||
const context = useContext(WebSocketContext); | ||
if (!context) { | ||
throw new Error('useWebSocket must be used within a WebSocketProvider'); | ||
} | ||
return context; | ||
} | ||
|
||
interface WebSocketProviderProps { | ||
children: ReactNode; | ||
} | ||
|
||
export function WebSocketProvider({ children }: WebSocketProviderProps) { | ||
const [socket, setSocket] = useState<WebSocket | null>(null); | ||
const [messages, setMessages] = useState<string[]>([]); | ||
const [connectionStatus, setConnectionStatus] = useState<string>('Disconnected'); | ||
|
||
useEffect(() => { | ||
const newSocket = new WebSocket('ws://127.0.0.1:8080'); | ||
|
||
newSocket.onopen = () => { | ||
console.log('WebSocket connected'); | ||
setConnectionStatus('Connected'); | ||
}; | ||
|
||
newSocket.onmessage = (event) => { | ||
const newMessage = event.data; | ||
setMessages((prevMessages) => [...prevMessages, newMessage]); | ||
}; | ||
|
||
newSocket.onclose = () => { | ||
console.log('WebSocket connection closed'); | ||
setConnectionStatus('Disconnected'); | ||
}; | ||
|
||
setSocket(newSocket); | ||
|
||
return () => { | ||
newSocket.close(); | ||
}; | ||
}, []); | ||
|
||
const sendMessage = (message: string) => { | ||
if (socket && socket.readyState === WebSocket.OPEN) { | ||
socket.send(message); | ||
} | ||
}; | ||
|
||
return ( | ||
<WebSocketContext.Provider value={{ messages, sendMessage, connectionStatus }}> | ||
{children} | ||
</WebSocketContext.Provider> | ||
); | ||
} |
Oops, something went wrong.