| | |
| | |
| | |
| | |
| | |
| | |
| |
|
| | import { useRef, useCallback } from 'react'; |
| |
|
| | const useWebsocket = (token, onOpen, onMessage, selectedModel) => { |
| | const socketRef = useRef(null); |
| |
|
| | |
| | const connectSocket = useCallback(() => { |
| | if (!socketRef.current) { |
| | const clientId = Math.floor(Math.random() * 1010000); |
| | const ws_scheme = window.location.protocol === "https:" ? "wss" : "ws"; |
| | |
| | |
| | var currentHost = window.location.host; |
| |
|
| | |
| | var parts = currentHost.split(':'); |
| |
|
| | |
| | var ipAddress = parts[0]; |
| | var currentPort = parts[1]; |
| |
|
| | |
| | var newPort = '8000'; |
| |
|
| | |
| | var newHost = ipAddress + ':' + newPort; |
| |
|
| | const ws_path = ws_scheme + '://' + newHost + `/ws/${clientId}?llm_model=${selectedModel}&token=${token}`; |
| | |
| | socketRef.current = new WebSocket(ws_path); |
| | const socket = socketRef.current; |
| | socket.binaryType = 'arraybuffer'; |
| | socket.onopen = onOpen; |
| | socket.onmessage = onMessage; |
| | socket.onerror = (error) => { |
| | console.log(`WebSocket Error: ${error}`); |
| | }; |
| | socket.onclose = (event) => { |
| | console.log("Socket closed"); |
| | }; |
| | } |
| | }, [onOpen, onMessage]); |
| |
|
| | |
| | const send = (data) => { |
| | console.log("message sent to server"); |
| | if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) { |
| | socketRef.current.send(data); |
| | } |
| | }; |
| |
|
| | const closeSocket = () => { |
| | socketRef.current.close(); |
| | socketRef.current = null; |
| | } |
| |
|
| | return { socketRef, send, connectSocket, closeSocket }; |
| | }; |
| |
|
| | export default useWebsocket; |
| |
|