Start with websocket backend connection

This commit is contained in:
qvalentin 2023-01-21 11:18:41 +01:00
parent 739c05daa1
commit 279d7ea502
4 changed files with 56 additions and 1 deletions

View File

@ -1,3 +1,4 @@
const JITSI_DOMAIN = "thisisnotajitsi.filefighter.de"; const JITSI_DOMAIN = "thisisnotajitsi.filefighter.de";
const WEBSOCKET_URL = "ws" + (window.location.protocol == "https:" ? "s" : "") + "://" + window.location.host + "/ws"
export { JITSI_DOMAIN }; export { JITSI_DOMAIN, WEBSOCKET_URL };

View File

@ -0,0 +1,20 @@
import useWebSocketConnection from "./useWebSocketConnection";
function useBackendData() {
const { onMessage, sendMessage } = useWebSocketConnection();
const { roomData, setRoomData } = useRoomData()
onMessage(
(messageString) => {
const messageObject = JSON.parse(messageString)
!!messageObject.roomData && setRoomData(messageObject.roomData)
}
)
}

View File

View File

@ -0,0 +1,34 @@
import { useCallback, useState } from "react";
import { WEBSOCKET_URL } from "../background/constants";
function useWebSocketConnection() {
const createWebSocketConnection = () => {
const webSocket = new WebSocket(WEBSOCKET_URL);
return webSocket
}
const [webSocketConnection] = useState<WebSocket>(createWebSocketConnection())
const sendMessage = useCallback((message: string) => {
//if the socket's open, send a message:
if (webSocketConnection.readyState === WebSocket.OPEN) {
webSocketConnection.send(message);
}
},
[webSocketConnection]
)
const onMessage = useCallback(
(messageHandler: (messageHandler: string) => void) => {
const wsMessageHandler = (ev: MessageEvent<any>) => { messageHandler(ev.data) }
webSocketConnection.addEventListener('message', wsMessageHandler)
},
[webSocketConnection]
)
return { onMessage, sendMessage }
}
export default useWebSocketConnection;