protohackers/main.ts
2022-10-06 12:47:45 -05:00

26 lines
878 B
TypeScript

const PORT = 5588;
console.log(`Starting UDP listener on port ${PORT}`);
const tDec = new TextDecoder();
const tEnc = new TextEncoder();
const reservedData: Record<string, string> = { version: "KeyVal 1.0" };
const data = new Map<string, string>();
const listener = Deno.listenDatagram({ port: PORT, transport: "udp" });
for await (const [bytes, addr] of listener) {
const message = tDec.decode(bytes).trim();
console.debug("Datagram Received from:", addr, message);
if (message.includes("=")) {
const [key, val] = message.split("=", 1);
console.debug(`Setting ${key} to ${val}`);
if (!(key in reservedData)) data.set(key, val);
} else {
const value = reservedData[message] || data.get(message) || "";
const bytes = tEnc.encode(`${message}=${value}`);
console.debug(`Sending ${message}=${value}`);
await listener.send(bytes, addr);
}
}