mlpcardgame/src/network/PeerClient.ts

56 lines
1.3 KiB
TypeScript

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("close", () => {
this.emit("disconnected");
});
this.connection.on("error", err => {
this.emit("error", err);
});
this.connection.on("data", data => {
this._received(data);
});
}
public get name(): string {
return this.metadata.name;
}
public get id(): string {
return this.peer.id;
}
public send<T extends NetworkMessage>(data: T) {
if (!this.connection) {
throw new Error("Client is not connected to a server");
}
this.connection.send(data);
}
}
export default PeerClient;