WebTransport 使用
约 301 字大约 1 分钟
2025-01-23
WebTransport API 提供了对 WebSockets 的现代更新,使用 HTTP/3 传输在客户端和服务器之间传输数据。WebTransport 支持多个流、单向流和无序传输。它支持通过流进行可靠传输,并通过类似 UDP 的数据报实现不可靠的传输。
注意 WebTransport 需要在 HTTPS 环境中使用,并且需要支持 HTTP/3。 HTTP/3 底层使用的 QUIC 协议支持多路复用,这意味着多个请求和响应可以在单个连接上同时进行,而不会相互干扰。TCP 层协议使用的是 UDP 协议,因此 WebTransport 可以实现低延迟和高吞吐量。
注意 WebTransport API 是一个实验性 API,可能会在未来的版本中发生变化。
使用
const url = "";
async function initTransport(url) {
// Initialize transport connection
const transport = new WebTransport(url);
// The connection can be used once ready fulfills
await transport.ready;
// ...
}
// ...
async function closeTransport(transport) {
// Respond to connection closing
try {
await transport.closed;
console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
} catch (error) {
console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
}
}