Many applications, such as games and live broadcasts, require a mechanism to send messages as quickly as possible while accepting disorderly and unreliable data transmission methods. While native applications can use raw UDP sockets, these are not available on the web because they lack encryption, congestion control, and consent-to-send mechanisms (to prevent DDoS attacks).
Typically, web applications that require bidirectional data flow exchange between client and server can rely on WebSockets, a message-based protocol that is compatible with the web security model. However, because WebSockets is a single, reliable, ordered message stream, it is subject to head-of-line blocking (HOLB), which means that all messages must be sent and received in order, even if they are independent of each other.
This makes WebSockets less suitable for applications that sacrifice reliability and stream independence to improve performance.
The WebTransport protocol provides a single transport object for this purpose, which abstracts a specific underlying protocol with a flexible set of capabilities, including reliable one-way, two-way streams, and unreliable datagrams ability.
WebTransport is a protocol framework for sending and receiving data from a server using HTTP3. Similar to WebSockets, but supports multi-stream, one-way stream, out-of-order transmission, and supports reliable and unreliable data transmission methods.
WebTransport is a Web API that uses the HTTP/3 protocol at the bottom to achieve bidirectional transmission. It is used as a bidirectional communication mechanism between clients and HTTP/3 servers. Supports unreliable data transmission through datagram API and reliable data transmission through streaming API. At the same time, close existing connections in scenarios where the client and server do not need to connect.
2.1 Datagram mode
The datagram mode is suitable for sending and receiving. Delivered data needs to be strictly guaranteed. The size of a single packet is limited by the maximum transmission unit of the underlying connection, so transmission is not guaranteed and, if successful, may arrive in any order. These properties make the Datagram API ideal for low-latency, best-effort delivery. Think of data transfer as User Datagram Protocol (UDP) messages, but with encryption and congestion control.
// 发送数据报 const writer = transport.datagrams.writable.getWriter(); const data1 = new Uint8Array([65, 66, 67]); const data2 = new Uint8Array([68, 69, 70]); // Uint8Array writer.write(data1); writer.write(data2); // 从服务器读取数据报 const reader = transport.datagrams.readable.getReader(); while (true) { const {value, done} = await reader.read(); // done则退出 if (done) { break; } // 值为 Uint8Array。 console.log(value); }
2.2 Streaming API method
Streaming API provides reliable and orderly data transmission, which is very suitable for sending or receiving a or Scenarios for multiple ordered data streams. Using multiple WebTransport streams is similar to establishing multiple TCP connections, but because HTTP/3 uses the lightweight QUIC protocol under the hood, the cost of creating and closing connections is lower.
Send stream
// 发送Uint8Array const stream = await transport.createSendStream(); const writer = stream.writable.getWriter(); const data1 = new Uint8Array([65, 66, 67]); const data2 = new Uint8Array([68, 69, 70]); // 实例化Uint8Array writer.write(data1); writer.write(data2); try { await writer.close(); // 所有数据已经传输 // await writer.abort(); // 如果调用abort并非所有数据都写入 } catch (error) { console.error(`An error occurred: ${error}`); }
Read stream
async function readFrom(receiveStream) { const reader = receiveStream.readable.getReader(); while (true) { const {done, value} = await reader.read(); if (done) { break; } // 值为 Uint8Array console.log(value); } } const rs = transport.receiveStreams(); // 返回一个 ReadableStream,ReadableStream 的每个块又是一个 ReceiveStream // 用于读取服务器发送的 Uint8Array 实例 const reader = rs.getReader(); while (true) { const {done, value} = await reader.read(); if (done) { break; } // 值为 ReceiveStream 的一个实例 await readFrom(value); }
Bidirectional stream
Bidirectional streams can be created by the server or the client:
async function setUpBidirectional() { const stream = await transport.createBidirectionalStream(); // stream 是 WebTransportBidirectionalStream // stream.readable是ReadableStream const readable = stream.readable; // stream.writable是WritableStream const writable = stream.writable; }
You can listen to the BidirectionalStream created by the server using the
receiveBidirectionalStreams() method of the WebTransport instance , this method returns ReadableStream. Each chunk of the ReadableStream is in turn a BidirectionalStream.
const rs = transport.receiveBidrectionalStreams();const reader = rs.getReader();while (true) { const {done, value} = await reader.read(); if (done) { break; } // value 是 BidirectionalStream // value.readable 是 ReadableStream // value.writable 是 WritableStream}
3.1 WebTransport development history
WebTransport was first proposed around May 2019, and the latest update was on January 24, 2023. Therefore, judging from the update time and update frequency, the protocol is still in the It is a period of change and rapid development, but it deserves continued attention from developers.
3.2 Browser supportCurrently, the overall browser support rate of WebTransport has reached about 70.29%, Chrome>=97, Edge>=98, Opera> ;=83 and other mainstream browsers already support it. Except for Firefox, the latest version 111 does not yet support it.
However, by using WebTransport through the Datagram API or multiple concurrent Streams API instances, you don't have to worry about queue blocking and other problems that WebSockets often encounter. Additionally, there are performance benefits when establishing new WebTransport connections because the underlying QUIC handshake is faster than initiating TCP over TLS.
However, since WebTransport technology has not yet been fully finalized, there are few development tools, and the ecosystem is imperfect, it may continue for some time. It's too early to predict whether WebTransport will replace Websockets, but the first teams to use it have every chance of building something groundbreaking. While there's no pressing need to switch, developers should keep an eye on it for future projects and be prepared to use it when it makes the most sense.
5. Summary of this article
The above is the detailed content of Does the browser support WebTransport? Can it replace WebSockets?. For more information, please follow other related articles on the PHP Chinese website!