W3cubDocs

/Web APIs

WebTransport: createBidirectionalStream() method

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The createBidirectionalStream() method of the WebTransport interface opens a bidirectional stream; it returns a WebTransportBidirectionalStream object containing readable and writable properties, which can be used to reliably read from and write to the server.

"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than datagrams, but is needed in situations where reliability and ordering are important, like chat applications.

Note: This feature is available in Web Workers

Syntax

createBidirectionalStream();

Parameters

None.

Return value

Exceptions

InvalidStateError DOMException

Thrown if createBidirectionalStream() is invoked while the WebTransport is closed or failed.

Examples

An initial function is used to get references to the WebTransportBidirectionalStream.readable and WebTransportBidirectionalStream.writable properties. These are references to ReadableStream and WritableStream instances, which can be used to read from and write to the server.

async function setUpBidirectional() {
  const stream = await transport.createBidirectionalStream();
  // stream is a WebTransportBidirectionalStream
  // stream.readable is a ReadableStream
  const readable = stream.readable;
  // stream.writable is a WritableStream
  const writable = stream.writable;

  ...
}

Reading from the ReadableStream can then be done as follows:

async function readData(readable) {
  const reader = readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}

And writing to the WritableStream can be done like this:

async function writeData(writable) {
  const writer = writable.getWriter();
  const data1 = new Uint8Array([65, 66, 67]);
  const data2 = new Uint8Array([68, 69, 70]);
  writer.write(data1);
  writer.write(data2);
}

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
createBidirectionalStream 97 97 No No 83 No 97 97 No 68 No 18.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/WebTransport/createBidirectionalStream