51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import { copy } from "https://deno.land/std@0.157.0/streams/conversion.ts?s=copy";
|
|
import { Buffer } from "https://deno.land/std@0.157.0/io/buffer.ts";
|
|
import { ByteSet } from "https://deno.land/x/bytes@1.0.3/mod.ts";
|
|
|
|
const QUERY_SIZE = 9;
|
|
const PORT = 5588;
|
|
|
|
const listener = Deno.listen({ port: 5588 });
|
|
|
|
console.log(`Listening on 0.0.0.0:${PORT}`);
|
|
|
|
for await (const conn of listener) {
|
|
console.log("Connection established:", conn.remoteAddr);
|
|
try {
|
|
meansToAnEnd(conn);
|
|
} catch (e) {
|
|
console.error(conn.remoteAddr, e);
|
|
}
|
|
console.log("Connection closed:", conn.remoteAddr);
|
|
}
|
|
|
|
// problem 2
|
|
async function meansToAnEnd(conn: Deno.Conn) {
|
|
try {
|
|
for await (const query of queries(conn)) {
|
|
console.log("Query:", query);
|
|
conn.write(ByteSet.from(Uint8Array.from([0]), "big").buffer);
|
|
}
|
|
console.log("Done!");
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
function queries(conn: Deno.Conn) {
|
|
return {
|
|
async *[Symbol.asyncIterator]() {
|
|
const b = new Uint8Array(1024);
|
|
const q = new Uint8Array();
|
|
let bytesRead = 0;
|
|
console.debug(b.length);
|
|
while (bytesRead < QUERY_SIZE) {
|
|
const n = await conn.read(b);
|
|
bytesRead += n;
|
|
console.debug(n, b.length);
|
|
}
|
|
yield q;
|
|
},
|
|
};
|
|
}
|