/
ivaninvv
/
minus-5
Обзор
Документация
Войти
/
ivaninvv
/
minus-5
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/network/NetworkManager.ts
66 строк
2 KB
Vladimir Ivanin
линтер
13 дек 2025, 23:25
13 дек 2025, 23:25
da0f563
Код
Авторство
О чём код?
import Peer, { DataConnection } from 'peerjs'; export class NetworkManager { private peer: Peer; private conn: DataConnection | null = null; public onData: ((data: unknown) => void) | null = null; public onConnected: (() => void) | null = null; constructor() { // PeerJS will connect to default cloud server this.peer = new Peer(); this.peer.on('open', (id) => { console.log('Peer ID:', id); }); this.peer.on('connection', (conn) => { console.log('Incoming connection...'); this.handleConnection(conn); }); this.peer.on('error', (err) => { console.error('Peer error:', err); }); } public getMyId(): Promise<string> { return new Promise((resolve) => { if (this.peer.id) resolve(this.peer.id); else this.peer.on('open', (id) => resolve(id)); }); } public connect(peerId: string) { console.log('Connecting to:', peerId); const conn = this.peer.connect(peerId); this.handleConnection(conn); } private handleConnection(conn: DataConnection) { this.conn = conn; conn.on('open', () => { console.log('Connection open!'); if (this.onConnected) this.onConnected(); }); conn.on('data', (data) => { // console.log('Received:', data); if (this.onData) this.onData(data); }); conn.on('close', () => { console.log('Connection closed'); this.conn = null; }); } public send(data: unknown) { if (this.conn && this.conn.open) { this.conn.send(data); } else { console.warn('Cannot send, connection not open'); } } }