WebTransport: createBidirectionalStream() method
The createBidirectionalStream()
method of the WebTransport
interface asynchronously opens and returns a bidirectional stream.
The method returns a Promise
that resolves to a WebTransportBidirectionalStream
object, which has readable
and writable
properties that 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
js
createBidirectionalStream()
Parameters
None
Return value
A Promise
that resolves to a WebTransportBidirectionalStream
object.
Exceptions
InvalidStateError
DOMException
-
Thrown if
createBidirectionalStream()
is invoked while theWebTransport
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.
js
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:
js
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:
js
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
Specification |
---|
WebTransport # dom-webtransport-createbidirectionalstream |
Browser compatibility
BCD tables only load in the browser