Hamcha
6f6b00fd05
Added PeerJS-powered client/server architecture. Clients can join, leave, chat rooms, Server can take parts as players too via a local client shim. Closes #4 Signed-off-by: Hamcha <hamcha@crunchy.rocks>
45 lines
1.1 KiB
TypeScript
45 lines
1.1 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("data", data => {
|
|
this._received(data);
|
|
});
|
|
}
|
|
|
|
public get name(): string {
|
|
return this.metadata.name;
|
|
}
|
|
|
|
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;
|