base2020/src/net/LoopbackServer.ts

68 lines
2.3 KiB
TypeScript

import { Callbag } from "callbag";
import pipe from "callbag-pipe";
import share from "callbag-share";
import { TICK_LENGTH } from "../ecs/Lockstep";
import {
catchTalkback,
defer,
interval,
lazy,
makeSubject,
map,
merge,
} from "../utilities/Callbag";
import { ClientMessage, MessageTypes, ServerMessage } from "./LockstepClient";
const heloSource: Callbag<never, ServerMessage<never, never>> = lazy(() => ({ t: MessageTypes.META, helo: "In-Process Loopback Server" }));
/** Stub loopback server that handles multiple clients, for schemes where GlobalInput = LocalInput[] */
export class LoopbackServer<LocalInput, State> {
private nextClientId = 0;
private inputBuffer: LocalInput[] = [];
private heartbeat = pipe(
interval(TICK_LENGTH),
map(() => ({
t: MessageTypes.INPUT,
i: this.inputBuffer.slice()
} as ServerMessage<LocalInput[], State>)),
);
private broadcast = makeSubject<ServerMessage<LocalInput[], State>>();
private serverFeed = share(merge(this.heartbeat, this.broadcast));
public readonly socket = defer(() => {
const playerNumber = this.nextClientId++;
return pipe(
merge(this.serverFeed, heloSource),
catchTalkback((message: ClientMessage<LocalInput, State>) => this.processMessage(playerNumber, message)),
map(message => this.postprocessResponse(playerNumber, message))
);
});
private processMessage(playerNumber: number, message: ClientMessage<LocalInput, State>) {
switch (message.t) {
case MessageTypes.INPUT:
if (playerNumber >= 0) {
this.inputBuffer[playerNumber] = message.i;
}
break;
case MessageTypes.SET_STATE:
this.broadcast(1, { t: MessageTypes.SET_STATE, u: -1, s: message.s });
break;
}
}
private postprocessResponse(playerNumber: number, message: ServerMessage<LocalInput[], State>): ServerMessage<LocalInput[], State> {
if (message.t === MessageTypes.SET_STATE && playerNumber >= 0) {
return {
...message,
u: playerNumber,
};
} else {
return message;
}
}
}