IMHO, HTTP2 Server sent events has rich features than HTTP Streaming.
In a unidirectional data flow (Server -> Client) where client side could be orchestrated based on backend events, server sent events could be a good choice.
For example:
# ---------- client side -----------
const eventSource = new EventSource("//your-api/workflow/state");
eventSource.addEventListener("queued", function(event) {
...
}
eventSource.addEventListener("started", function(event) {
...
}
eventSource.addEventListener("failed", function(event) {
...
}
eventSource.addEventListener("success", function(event) {
...
}
Limitations of Server sent events:
- SSE events consume browser open connections.
- There is a limit on number of max open connections not at browser tab level but whole browser level
- The time I am writing, Chrome & Firefox has it as 6 (too low). This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com.
HTTP Streaming
There are many use cases where HTTP streaming could be useful. If we are only interested in a stream of message from Server, this could be handy.
Example scenario :
Let's say we like to stream a log file content to client. Either it could be a huge file or the file content keeps updating and we like to send it to client (like a log tail). In such case, HTTP stream (Transfer-Encoding: chunked
) could satisfy our needs.
# ---------- client side -----------
const streamRequest = (url) => {
fetch(url).then(function (response) {
let reader = response.body.getReader();
let decoder = new TextDecoder();
return readData();
function readData() {
return reader.read().then(function ({value, done}) {
console.log(value)
if (value) {
let newData = decoder.decode(value, {stream: !done});
console.log(newData);
}
if (done) {
console.log('end of stream');
return;
}
return readData();
});
}
});
}
Limitations of Stream response:
- In case of stream response (chunked) - HTTP/2 doesn't support HTTP 1.1's chunked transfer encoding mechanism, as it provides its own, more efficient, mechanisms for data streaming.