58 lines
1.4 KiB
TypeScript
58 lines
1.4 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import Peer from "peerjs";
|
|
|
|
export default function usePeerManager() {
|
|
const [peerId, setPeerId] = useState<string | null>(null);
|
|
const [peers, setPeers] = useState<string[]>([]);
|
|
const peerRef = useRef<Peer | null>(null);
|
|
const connectionsRef = useRef<Map<string, any>>(new Map());
|
|
|
|
useEffect(() => {
|
|
const peer = new Peer();
|
|
peerRef.current = peer;
|
|
|
|
peer.on("open", (id) => {
|
|
setPeerId(id);
|
|
});
|
|
|
|
peer.on("connection", (conn) => {
|
|
conn.on("open", () => {
|
|
connectionsRef.current.set(conn.peer, conn);
|
|
setPeers(Array.from(connectionsRef.current.keys()));
|
|
});
|
|
|
|
conn.on("data", (data) => {
|
|
console.log("Received:", data);
|
|
});
|
|
|
|
conn.on("close", () => {
|
|
connectionsRef.current.delete(conn.peer);
|
|
setPeers(Array.from(connectionsRef.current.keys()));
|
|
});
|
|
});
|
|
|
|
return () => {
|
|
peer.destroy();
|
|
};
|
|
}, []);
|
|
|
|
const connectToPeer = (id: string) => {
|
|
if (!peerRef.current) return;
|
|
const conn = peerRef.current.connect(id);
|
|
|
|
conn.on("open", () => {
|
|
connectionsRef.current.set(conn.peer, conn);
|
|
setPeers(Array.from(connectionsRef.current.keys()));
|
|
});
|
|
};
|
|
|
|
const broadcast = (data: any) => {
|
|
connectionsRef.current.forEach((conn) => {
|
|
if (conn.open) conn.send(data);
|
|
});
|
|
};
|
|
|
|
return { peerId, peers, connectToPeer, broadcast };
|
|
} |