Besides for browsers, which do not expose HTTP/2 frames to Javascript, in what case would Websockets be a better choice than something like bidirectional streaming gRPCs (built on HTTP/2) for implementing real-time bidirectional message streams? Also, doesn't HTTP 2.0 being full-duplex (and bidirectional) mean that server pushes are in fact supported? What is the need for something like SSE, then? This is made obsolete, right?
There is many aspects here. Server Sent Events, JavaScript Streams API is mostly browser APIs for lower level protocols.
Server to Server communication
Server to Server communication using Websockets and HTTP/2 has similar properties. Both are binary and efficient protocols. HTTP/2 provides per stream backpressure which can be important for clients that receives push messages from multiple sources or may be busy at times. gRPC is a framework on top of HTTP/2 and provides a higher abstraction to the developer.
Server to Browser communication
Server Sent Events
Server Sent Events is a way for a client to subscribe to an event stream and continuously receive events from a server. The API is a higher abstraction and easier to use than alternatives. However the format is a specified message format in text.
Developing a web application that uses server-sent events is easier than with websockets. You'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to handling any other event.
Example code
const evtSource = new EventSource("/v1/stream/topic");
evtSource.onmessage = function(event) {
// handle event
}
JavaScript Streams API
JavaScript Streams API is a newer JavaScript API for supporting binary streams between browser and server. This can be used with the newer ReadableStream from Fetch API. Since this is a binary stream, it can have a broader use case and may be important for applications using e.g. webassembly in upcoming years.
The API is a bit more complex. Example code:
fetch("https://www.example.org/").then((response) => {
const reader = response.body.getReader();
const stream = new ReadableStream({
start(controller) {
// implementation
}
})
The advantage with a binary stream is that it may be used for naturally binary data e.g. audio or binary respresentations of custom formats.
Using JavaScript Streams API on HTTP/2 or HTTP/3 Streams has the advantage over alternatives in that it supports backpressure per stream (not only per TCP connection).
gRPC
gRPC is a protocol using HTTP/2 streams, but it is not implemented on the JavaScript Streams API, so for browser communication it needs some middleware like grpc-web.
WebSockets
WebSockets is a lower level abstraction and it has broader browser support and it supports full-duplex communication. But since it is a lower level abstraction it often requires libraries to handle the communication.
© 2022 - 2024 — McMap. All rights reserved.