Search code examples
javascripttcpdeno

Dynamically sized Uint8Array when receiving data over TCP network


I have successfully built a simple TCP server, here is my code:

const server = Deno.listen({ port:3000 })

for await (const conn of server) {
  let d = new Uint8Array(1024)

  await conn.read(d)

  console.log(d)
}

This works well, at some point, it’s not a big problem. However I don’t want to manually set the Uint8Array size and slices the uint8array by length received from conn.read().

Is there any workaround to handle this?

Dynamically sized Uint8Array that received from conn.read()


Solution

  • Two ways:

    Iterate the ReadableStream:

    const server = Deno.listen({ port: 3000 });
    
    for await (const conn of server) {
      (async () => {
        const byteArr: number[] = [];
        for await (const chunk of conn.readable) byteArr.push(...chunk);
        const u8Arr = new Uint8Array(byteArr);
      })();
    }
    

    Use readAll from deno.land/std:

    import { readAll } from "https://deno.land/[email protected]/streams/conversion.ts";
    
    const server = Deno.listen({ port: 3000 });
    
    for await (const conn of server) {
      (async () => {
        const u8Arr = await readAll(conn);
      })();
    }
    

    You can read the source for Buffer#readFrom to learn how readAll does it internally.

    Be sure to read the manual page HTTP Server APIs (low level) | Manual | Deno, as it covers a lot of what you seem to be exploring/asking about.