protohackers/6.ts
2022-11-19 20:43:14 -06:00

34 lines
887 B
TypeScript

import { BufReader } from "https://deno.land/std@0.157.0/io/buffer.ts";
const PORT = 5588;
// const tEnc = new TextEncoder();
console.log(`Starting TCP listener on on 0.0.0.0:${PORT}`);
function chatSession(conn: Deno.Conn) {
const closeOnDisconnect = () => {
console.warn("Disconnected client");
try {
conn.close();
} catch (err) {
console.error("Error closing client connection:", err);
}
};
serve(conn).catch((e) => e).finally(closeOnDisconnect);
}
async function serve(conn: Deno.Conn) {
const reader = new BufReader(conn);
const type = await reader.peek(1);
if (!type) throw new Error("failed to peek start of packet");
console.log(type);
}
for await (const conn of Deno.listen({ port: PORT })) {
console.log("Connection established:", conn.remoteAddr);
chatSession(conn);
console.log("Connection closed:", conn.remoteAddr);
}