WebTransportBidirectionalStream
The WebTransportBidirectionalStream interface of the WebTransport API represents a bidirectional stream created by a server or a client that can be used for reliable transport. Provides access to a ReadableStream for reading incoming data, and a WritableStream for writing outgoing data.
Instance properties
readable Read only
-
Returns a ReadableStream instance that can be used to read incoming data.
writable Read only
-
Returns a WritableStream instance that can be used to write outgoing data.
Examples
Bidirectional transmission initiated by the user agent
To open a bidirectional stream from a user agent, you use the WebTransport.createBidirectionalStream() method to get a reference to a WebTransportBidirectionalStream. The readable and writable properties return 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();
const readable = stream.readable;
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;
}
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);
}
Bidirectional transmission initiated by the server
If the server opens a bidirectional stream to transmit data to and receive it from the client, this can be accessed via the WebTransport.incomingBidirectionalStreams property, which returns a ReadableStream of WebTransportBidirectionalStream objects. Each one can be used to read and write Uint8Array instances as shown above. However, you need an initial function to read the bidirectional stream in the first place:
async function receiveBidirectional() {
const bds = transport.incomingBidirectionalStreams;
const reader = bds.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
await readData(value.readable);
await writeData(value.writable);
}
}
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 |
WebTransportBidirectionalStream |
97 |
97 |
114 |
No |
83 |
No |
97 |
97 |
114 |
68 |
No |
18.0 |
readable |
97 |
97 |
114 |
No |
83 |
No |
97 |
97 |
114 |
68 |
No |
18.0 |
writable |
97 |
97 |
114 |
No |
83 |
No |
97 |
97 |
114 |
68 |
No |
18.0 |
See also