86 lines
2.1 KiB
JavaScript
86 lines
2.1 KiB
JavaScript
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) {
|
|
|
|
var url = url.startsWith('/')? url: '/' + url
|
|
console.log(
|
|
`ws://${process.env.NEXT_PUBLIC_HOSTNAME}:${process.env.NEXT_PUBLIC_PORT}${url}`
|
|
);
|
|
ws.current = new ReconnectingWebSocket(
|
|
`ws://${process.env.NEXT_PUBLIC_HOSTNAME}:${process.env.NEXT_PUBLIC_PORT}${url}`
|
|
);
|
|
|
|
ws.current.onopen = () => {
|
|
setConnected(true);
|
|
};
|
|
ws.current.onmessage = (e) => {
|
|
messageHandlers.forEach((handler) => {
|
|
handler(e);
|
|
});
|
|
};
|
|
ws.current.onclose = (c) => {
|
|
|
|
setConnected(false);
|
|
};
|
|
ws.current.onerror = (e) => {
|
|
|
|
|
|
//router.push({ pathname: '/room/join' })
|
|
ws.current.close();
|
|
};
|
|
}
|
|
};
|
|
const disconnect = () => {
|
|
if (ws != null && ws.current != null ) {
|
|
ws.current.close();
|
|
setConnected(false)
|
|
}
|
|
};
|
|
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={{
|
|
ws,
|
|
send,
|
|
connect,
|
|
addMessageHandler,
|
|
removeMessageHandler,
|
|
isConnected,
|
|
disconnect,
|
|
}}
|
|
>
|
|
{children}
|
|
</WebsocketContext.Provider>
|
|
);
|
|
};
|