Generateurv2/frontend/context/websocket.context.js

78 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-05-18 10:15:54 +02:00
import { useRouter } from "next/router";
import { createContext, useContext, useRef, useState } from "react";
import ReconnectingWebSocket from "reconnecting-websocket";
import { isBrowser } from "../utils/utils.js";
export const WebsocketContext = createContext({});
2022-06-24 13:42:16 +02:00
export const useWebsocketContext = () => {
return useContext(WebsocketContext);
};
2022-06-11 23:39:03 +02:00
2022-05-18 10:15:54 +02:00
export const WebsocketProvider = ({ children }) => {
const ws = useRef(null);
const [isConnected, setConnected] = useState(false);
2022-06-24 13:42:16 +02:00
const router = useRouter();
2022-05-18 10:15:54 +02:00
const connect = (url) => {
if (isBrowser) {
ws.current = new ReconnectingWebSocket(url);
ws.current.onopen = () => {
setConnected(true);
};
ws.current.onmessage = (e) => {
messageHandlers.forEach((handler) => {
handler(e);
});
};
ws.current.onclose = (c) => {
2022-06-24 13:42:16 +02:00
console.log("CLOSED", c);
2022-05-18 10:15:54 +02:00
setConnected(false);
};
ws.current.onerror = (e) => {
2022-06-24 13:42:16 +02:00
console.log("ERROR", e);
2022-05-18 10:15:54 +02:00
//router.push({ pathname: '/room/join' })
2022-06-24 13:42:16 +02:00
ws.current.close();
};
}
};
const disconnect = () => {
if (ws != null && ws.current != null ) {
ws.current.close();
setConnected(false)
2022-05-18 10:15:54 +02:00
}
};
const [messageHandlers, setMessageHandlers] = useState(new Set());
const addMessageHandler = (handler) => {
let newSet = messageHandlers;
newSet.add(handler);
setMessageHandlers(newSet);
};
const removeMessageHandler = (handler) => {
let newSet = messageHandlers;
newSet.delete(handler);
setMessageHandlers(newSet);
};
const send = (data) => {
if (ws.current != null) {
ws.current.send(JSON.stringify(data));
}
};
return (
<WebsocketContext.Provider
value={{
2022-06-24 13:42:16 +02:00
ws,
2022-05-18 10:15:54 +02:00
send,
connect,
addMessageHandler,
removeMessageHandler,
2022-06-24 13:42:16 +02:00
isConnected,
disconnect,
2022-05-18 10:15:54 +02:00
}}
>
{children}
</WebsocketContext.Provider>
);
};