Skip to content

Add test for WebSocketStream #8

Open

Description

@ValorZard

There's a new version of the WebSocket API in Chrome that might be interesting to test
https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream
whatwg/websockets#48

Activity

  1. guest271314 commented on Nov 4, 2025

    @guest271314

    Here's a JavaScript runtime agnostic implementation that can be tested in the browser, and by JavaScript runtimes; tested using Node.js, Deno, Bun, and txiki.js https://github.com/guest271314/websocket-stream-impl.

  2. guest271314 commented on Nov 4, 2025

    @guest271314

    FYI, this is one way I test WebSocketStream, just to get an idea of how the API with WHATWG Streams works. Send and get back 20 MB.

    var u8 = new Uint8Array(1024 ** 2 * 20).fill(1);
    var decoder = new TextDecoder();
    var encoder = new TextEncoder();
    
    var wss = new WebSocketStream("ws://127.0.0.1:44818");
    console.log(wss);
    
    var { readable, writable } = await wss.opened.catch(console.warn);
    
    var reader = readable.getReader();
    var writer = writable.getWriter();
    
    Promise.allSettled([writable.closed, readable.closed, wss.closed]).then((
      [,,{value}],
    ) => console.log(value)).catch(console.error);
    
    async function stream(data) {
      const len = 65536;
      let bytes = 0;
    
      if (typeof data === "string") {
        for (let i = 0; i < data.length; i += len) {
          await writer.ready;
          await writer.write(data.slice(i, i + len));
          const { value, done } = await reader.read();
          bytes += value.length;
        }
      } else {
        for (let i = 0; i < data.length; i += len) {
          const uint8 = data.subarray(i, i + len);
          await writer.ready;
          await writer.write(uint8);
          const { value, done } = await reader.read();
          bytes += value.byteLength;
        }
      }
      return bytes;
    }
    
    var binaryResult = await stream(u8).catch((e) => e);
    var textResult = await stream("text").catch((e) => e);
    
    console.log({
      binaryResult,
      textResult,
    });
    
    wss.close({
      closeCode: 4999,
      reason: "Done streaming",
    });
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions