p2p poll logic added
This commit is contained in:
58
hooks/usePeerManager.ts
Normal file
58
hooks/usePeerManager.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
"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 };
|
||||
}
|
||||
Reference in New Issue
Block a user