import Peer, { DataConnection } from "peerjs"; import { PeerMetadata, NetworkMessage } from "./types"; import Client from "./Client"; export class PeerClient extends Client { protected peer: Peer; private connection?: DataConnection; public constructor(metadata: PeerMetadata, customPeer?: Peer) { super(metadata); this.peer = customPeer ? customPeer : new Peer(); this.peer.on("open", function(id) { console.info("Peer ID assigned: %s", id); }); } public connect(peerid: string) { this.connection = this.peer.connect(peerid, { metadata: this.metadata, reliable: true }); if (!this.connection) { throw new Error("Could not connect"); } this.connection.on("open", () => { this.emit("connected"); }); this.connection.on("data", data => { this._received(data); }); } public get name(): string { return this.metadata.name; } public send(data: T) { if (!this.connection) { throw new Error("Client is not connected to a server"); } this.connection.send(data); } } export default PeerClient;