Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

WebSocketStream API

| Comments

WebSocketStream API came into play to make things easier with WebScoket API, which has the below limitations:

  • Ergonomics isn't great.
  • The important feature of backpressure is missing.
  • The onmessage event will keep firing until the page becomes completely unresponsive.
  • To find out when it is safe to start sending messages again, it is necessary to poll bufferedAmount.

Goals of WebSocketStream API:

  • Provide a WebSocket API that supports backpressure
  • Provide a modern, ergonomic, easy-to-use WebSocket API
  • Allow for future extension

^ From the explainer.

Sample code:

1
2
3
4
5
6
7
8
(async () => {
  const wss = new WebSocketStream("wss://echo.websocket.org/");
  const { readable, writable } = await wss.connection;
  const reader = readable.getReader();
  await writable.getWriter().write("echo");
  const { value, done } = await reader.read();
  console.log(value, done);
})();

DEMO:

Comments