WebTransport es una nueva API que ofrece mensajería cliente-servidor bidireccional de baja latencia. Obtenga más información sobre sus casos de uso y cómo dar comentarios sobre el futuro de la implementación.
Updated
Caution: This initiative has undergone important changes since the beginning of the Origin Trial. As of Chrome 87, WebTransport has replaced QuicTransport as the top-level interface that developers interact with.
Como consecuencia, parte de la información y todo el código de muestra de este post está desactualizado. Para conocer las últimas novedades sobre esta iniciativa en evolución, consulte el
WebTransport editor draft. Includes a Examples section with updated code snippets.
Once the initiative stabilizes, we will update this post and the associated code samples with updated information.
Background
What is QuicTransport?
QuicTransport es una API Web que usa QUIC protocolo en un transporte bidireccional, no HTTP. Está diseñado para comunicaciones bidireccionales entre un client web y un server QUIC. Admite el envío de datos de manera poco confiable mediante sus API de datagramas y de manera confiable mediante sus API de transmisión.
Datagrams they are ideal for sending and receiving data that does not need strong delivery guarantees. Individual data packets are limited in size by the maximum transmission unit (MTU) of the underlying connection, and may or may not be transmitted successfully, and if transferred, they may arrive in an arbitrary order. These features make Datagram APIs ideal for low-latency, best-effort data transmission. You can think of datagrams as user datagram protocol (UDP) messages, but encrypted and congestion controlled.
Streams APIs, by contrast, provide trustworthyorderly data transfer. They are well suited to scenarios where you need to send or receive one or more ordered data streams. Using various QUIC streams is analogous to determining various TCP connections, but QUIC flows are lightweight and can be opened and closed without much overhead.
What is WebTransport?
QuicTransport is a part of the greater WebTransport Initiative. WebTransport is a collection of APIs for sending and receiving data between a web client and a server. QuicTransport is the interface for using the QUIC protocol in the context of bidirectional WebTransport communications.
Chrome is implementing the QuicTransport part of WebTransport first, before any of the other proposed interfaces. The Chrome team has made the decision to start with QuicTransport after talking to web developers about their use cases. We hope to solicit early feedback on the overall WebTransport effort based on developers' experiences with QuicTransport.
Use cases
This is a short list of possible ways developers can use QuicTransport.
- Send game state at regular intervals with minimal latency to a server using small, unreliable, out-of-order messages.
- Receive media streams sent from a server with minimal latency, regardless of other data streams.
- Receive notifications sent from a server while a web page is open.
As part of the proof of origin procedure, we are interested in learning more about how you plan to use QuicTransport.
Actual state
He passed | Condition |
---|---|
1. Create an explainer | To complete |
2. Create initial draft specification | To complete |
3. Collect feedback and repeat the design | In progress |
4. Proof of origin | In progress |
5. Launch | Not started |
Linking QuicTransport with other technologies
Is QuicTransport a replacement for WebSockets?
Maybe. There are use cases where WebSockets or QuicTransport may be valid communication protocols to use.
WebSockets communications are modeled around a single, reliable, and ordered message stream, which is fine for some types of communication needs. If you require those features, the QuicTransport Streaming APIs can also provide them. By comparison, QuicTransport's Datagram APIs provide low-latency delivery, with no reliability or ordering guarantees, so they are not a direct replacement for WebSockets.
Using QuicTransport, either through the Datagram APIs or through multiple simultaneous Streams API instances, means you don't have to worry about head-of-line blocking, which can be a hindrance with WebSockets. At the same time, there are performance benefits in determining new connections, since Quick handshake it is faster than starting TCP over TLS.
QuicTransport is part of a new draft specification and as such the WebSocket ecosystem around the client and server libraries is now much stronger. If you require something that works "out of the box" with common server configurations and broad web client support, WebSockets is a better choice at this point.
Is QuicTransport the same as a UDP socket API?
No. QuicTransport is not a UDP socket API. Although QUIC uses UDP "under the hood", QuicTransport has requirements around encryption and congestion control that make it more than just a basic UDP Socket API.
Is QuicTransport an alternative to WebRTC data channels?
Yes, for client-server connections. QuicTransport shares many of the same properties as WebRTC data channels, even when the underlying protocols are different.
WebRTC data channels support peer-to-peer communications, but QuicTransport only supports client-server connection. If you have multiple clients who need to talk directly to each other, QuicTransport is not an option.
In general, running a QUIC-compliant server requires less installation and configuration than maintaining a WebRTC server, which means understanding various protocols (ICE, DTLSand SCTP) to get a working transport. WebRTC comes with many more moving parts that could lead to failed negotiations between client and server.
La API de QuicTransport se diseñó teniendo en cuenta los casos de uso de los desarrolladores web y debería sentirse más como escribir un código de plataforma web moderno que usar las interfaces de channel de datos de WebRTC. Unlike WebRTC, QuicTransport is supported within web employees, que le posibilita realizar comunicaciones cliente-servidor sin tener en cuenta una página HTML determinada. Debido a que QuicTransport expone un Currents-compatible interface, supports optimizations around back pressure.
However, if you already have a working WebRTC client/server setup that you're happy with, switching to QuicTransport may not offer much benefit.
test it
The best way to experiment with QuicTransport is to use this python code to start a supported QUIC server locally. You can then use this page with a basic JavaScript client to test client / server communications.
Using the API
QuicTransport was designed on the primitives of the modern web platform, such as Streams API. It relies heavily on promisesand it goes pretty well with async
and await
.
La prueba de origen de QuicTransport admite tres tipos distintos de traffic: datagramas, así como flujos unidireccionales y bidireccionales.
Connect to a server
You can connect to a QUIC server by creating a QuicTransport
ejemplo. El esquema de la Url must be quic-transport
. You must explicitly specify the port number.
you should use the ready
promises to wait for the connection to be established. This promise will not be fulfilled until the configuration is complete and will be rejected if the connection fails at the QUIC/TLS phase.
the closed
The promise is reached when the connection is closed regularly and is rejected if the closure was unexpected.
If the server rejects the connection due to a customer indication error (for example, the url path is invalid), then that causes closed
reject, while ready
remains unsolved.
const dirección url = 'quic-transport://example.com:4999/foo/bar';
const transport = new QuicTransport(dirección url);
transport.closed.then(() => {
console.log(`The QUIC connection to ${dirección url} closed gracefully.`);
}).catch((error) => {
console.error('The QUIC connection to ${dirección url} closed due to ${error}.');
});
await transport.ready;
Datagram API
Once you have an instance of QuicTransport that is connected to a server, you can use it to send and receive bits of discrete data, known as datagrams.
the sendDatagrams ()
the method returns a WritableStream
, which a web client can use to send data to the server. the receiveDatagrams ()
the method returns a ReadableStream
, which enables you to listen to data from the server. Both transmissions are inherently unreliable, so it is possible that the server will not receive the data you write, and vice versa.
Both types of currents use Uint8Array
instances for data transfer.
const ws = transport.sendDatagrams();
const writer = ws.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
const rs = transport.receiveDatagrams();
const reader = rs.getReader();
while (true) {
const {value, done} = await reader.read();
if (done) {
break;
}
console.log(value);
}
Chrome no right now expose a asynchronous iterator for ReadableStream
. At the moment, using the getReader ()
method combined with a while ()
loop is the best way to read from the sequence.
Streams API
Once you've connected to the server, you can also use QuicTransport to send and receive data using its Streams APIs.
Each part of all transmissions is a Uint8Array
. Unlike the datagram APIs, these streams are reliable. But each stream is independent, so the order of the data between the streams is not guaranteed.
SendStream
A SendStream
is created by the web client using the createSendStream ()
method of a QuicTransport
instance, which returns a promise for the SendStream
.
Use the close ()
method of WritableStreamDefaultWriter
associated with the sequence to send a QUIC Stream FIN bit al servidor. El browser intenta enviar todos los datos pendientes antes de cerrar el flujo QUIC asociado.
const stream = await transport.createSendStream();
const writer = stream.writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);
try {
await writer.close();
console.log('All data has been sent.');
} catch (error) {
console.error(`An error occurred: ${error}`);
}
In the same way, use the abort ()
method of WritableStreamDefaultWriter
to send a QUIC RESET_STREAM to the server. When you use abort ()
, the browser can discard any pending data that has not yet been sent.
const ws = await transport.createSendStream();
const writer = ws.getWriter();
writer.write(...);
writer.write(...);
await writer.abort();
ReceiveStream
A ReceiveStream
it is started by the server. get a ReceiveStream
it is a two-step procedure for a web client. First, call the receiveStreams ()
method of a QuicTransport
instance, which returns a ReadableStream
. Every piece of it ReadableStream
, is, in turn, a ReceiveStream
which can be used to read Uint8Array
instances submitted by the server.
async function readFrom(receiveStream) {
const reader = receiveStream.readable.getReader();
while (true) {
const {done, value} = await reader.read();
if (done) {
break;
}
console.log(value);
}
}const rs = transport.receiveStreams();
const reader = rs.getReader();
while (true) {
const {done, value} = await reader.read();
if (done) {
break;
}
await readFrom(value);
}
You can detect the closure of a stream using the closed
promise of ReadableStreamDefaultReader
. When the QUIC sequence is closed with the FIN bit, the closed
The promise is reached after reading all the data. When the QUIC flow is closed abruptly (by way of example, for STREAM_RESET
), So, the closed
promise rejected.
const reader = receiveStream.readable.getReader();
reader.closed.then(() => {
console.log('The receiveStream closed gracefully.');
}).catch(() => {
console.error('The receiveStream closed abruptly.');
});
BidirectionalStream
A BidirectionalStream
it can be created by the server or the client.
Web clients can create one using the createBidirectionalStream ()
method of a QuicTransport
instance, which returns a promise for a BidirectionalStream
.
const stream = await transport.createBidirectionalStream();
Can you hear a BidirectionalStream
created by the server with the receiveBidirectionalStreams ()
method of a QuicTransport
instance, which returns a ReadableStream
. Every piece of it 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;
}
}
A BidirectionalStream
it's just a combination of a SendStream
and ReceiveStream
. The examples in the previous two sections explain how to use each of them.
More examples
the WebTransport specification project includes several additional online examples, along with complete documentation of all methods and properties.
Enabling support during proof of origin
- Request a token by your origin.
- Add the token to your pages. There are two ways to do it:
- Add a
origin-trial
tag to the header of each page. As an example, this might look like this:
- If you can configure your server, you can additionally add the token using a
Origin-Trial
HTTP header. The resulting response header should look like this:Origin-Trial: TOKEN_GOES_HERE
- Add a
QuicTransport in Chrome DevTools
Unfortunately, Chrome DevTools the support for QuicTransport is not ready for the start of the proof of origin. Please "star" this chrome problem to receive notifications about updates in the DevTools interface.
Privacy and security considerations
Please see the respective section of the draft specification for an authoritative guide.
Feedback
The Chrome team wants to hear your thoughts and experiences using this API throughout the origin testing process.
Comments on the API design
Could there be something in the API that is awkward or not working as expected? Or missing parts you need to put your idea into practice?
Present an obstacle Web Transport GitHub Repositoryor add your thoughts to an existing obstacle.
Problem with the implementation?
Found a bug with the Chrome implementation?
File a bug in https://new.crbug.com. Include as much detail as you can, along with simple instructions for reproduction.
Do you plan to use the API?
Su soporte público ayuda a Chrome a priorizar funciones y muestra a otros proveedores de browsers lo importante que es brindarles soporte.
- Make sure you have signed up for the essay of origin para mostrar su interés y proporcionar su domain e información de contacto.
- Send a tweet to @Cromodev with
#QuicTransport
and details about where and how you are using it.
General Discussion
You can use the Web-transport-dev Google Group for general questions or problems that do not fit into any of the other categories.
Thanks
This post incorporates information from the WebTransport explainer, draft specificationand related design documents. Thanks to the respective authors for granting that base.
The main image of this post is from Robin pierre on Unsplash.