Generateurv2/frontend/context/websocket.context.js

103 lines
2.6 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({});
export const useWebsocketContext = ()=>{return useContext(WebsocketContext)}
export const WebsocketProvider = ({ children }) => {
const ws = useRef(null);
const [isConnected, setConnected] = useState(false);
const router = useRouter()
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) => {
console.log('CLOSED', c)
setConnected(false);
};
ws.current.onerror = (e) => {
console.log('ERROR', e)
//router.push({ pathname: '/room/join' })
ws.current.close()
}
}
};
/* const reconnect = (id_code, clientId) => {
if (ws.current == null && isBrowser) {
let tmpWs = new ReconnectingWebSocket(
`ws://192.168.1.18:8000/ws/room/${id_code}`
);
tmpWs.send(
JSON.stringify({
data: {
type: "reconnect",
clientId: clientId,
},
})
);
//setWs(tmpWs);
ws.current = tmpWs;
ws.current.onmessage = (e) => {
messageHandlers.forEach((handler) => {
handler(e);
});
};
tmpWs = null;
}
};
*/
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));
}
};
/* useEffect(() => {
if (isBrowser && ws != null) {
ws.onmessage = (e) => {
console.log("Handler principal", e);
messageHandlers.forEach((handler) => {
handler(e);
});
};
}
}, [ws, messageHandlers]); */
return (
<WebsocketContext.Provider
value={{
send,
connect,
addMessageHandler,
removeMessageHandler,
isConnected
}}
>
{children}
</WebsocketContext.Provider>
);
};