Hemanth's Scribes

web

WebSocketStream API

Author Photo

Hemanth HM

Thumbnail

WebSocketStream API came into play to make things easier with WebSocket 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

(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);
})();
#javascript#web-api#websocket#streams
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.