Can I stream a response back to the browser using

2019-08-03 05:59发布

问题:

Is it possible to stream a response back to the browser, from node, perhaps using http2?

In my web-app, a user presses a button which starts a server process. This process might take 10 minutes or longer to complete. I want to stream status updates back to the client/browser.

I believe I can do this with websockets, but I was hoping http2 had something to make this easier. I know it supports "push" but as far as I know, that's only for pushing files the user might need in the future.

Or maybe I don't even need http2? How long will the browser keep a connection open for? Can I just keep res.write()ing to it indefinitely?

回答1:

In principal you can stream data from a server to client with any HTTP version, just by sending only fragments of the data within the response body. However the current brower HTTP APIs (XHR and fetch) don't yet allow to read the response body in a streaming fashion, instead they will buffer the whole response (which does not make sense for an infinite stream). Working with a streamed response body will be possible in the future when the streaming feature of the fetch API is fully available, see: https://www.chromestatus.com/feature/5804334163951616 You can already use it on Chrome, but as far as I understand it's not fully standardized and broadly available yet.

An exception to this general rule are Server Sent Events (SSE), which are HTTP responses from the browser which follow a well defined transform encoding (text/event-stream). Browsers support the SSE APIs in order to work with SSE responses, and the SSE APIs allow you to get an event for each received data chunk. The API is fairly easy and you don't need to invent an own chunking mechanism, so it might be a good option for your application.

Regarding HTTP/1.1 and HTTP/2: The major difference that you would observe it the number of concurrent streams that you can create with them. For HTTP/1.1 each stream requires a full TCP connection, and browsers limit connections to a remote host (I think to less than 10). So creating 50 SSE streams is not possible - and I would go even further and would say you probably should only use a single SSE stream and put all event data in that. HTTP/2 on the other hand allows to multiplex lots of HTTP requests (and thereby also streamed body responses) on a single TCP connection, which means having a larger number of concurrent SSE streams is less of a problem there.