Streaming Response part 1: Server Sent Event
3 methods to stream response
In fact, to achieve the Streaming effect, you can use three methods:
Server Sent Event (SSE) => This is the method discussed in the current article
Transfer-Encoding: chunked=>You can refer to this article I wrote
Websocket: There are many tutorials about this online, so I didn't prepare a separate article on it
HTTP/2 Server Push is different with Server Sent Event
On the internet, there's a lot of talk about the differences and use cases between Websocket and Server Sent Event. Sometimes you might come across mentions of HTTP/2 Server Push, but there aren't as many articles comparing all three. Finally, in the following article, it's mentioned that HTTP/2 Server Push is indeed different from SSE.
Is HTTP/2 push a replacement for WebSockets or SSE?
一個關鍵點: HTTP/2 只有在 initial request 的時候可以多送 resource 給 client。 技術上來說 websocket 跟 server-sent-events (SSE) 允許 two-way flow,但是 HTTP/2 並不是真的 two-way。HTTP/2 還是依賴 client-side request。當 initial request 後,server 決定要多送 response 給 client, 當 request 結束後,這個 stream 也將被關閉。之後 server 沒有辦法透過此 stream 傳送任何 resource 給 client, 直到 client 又發送另一個 request 過來。
因此 HTTP/2 並不是一個 websocket 或者 SSE 的替代品。至少這階段不是,不過未來有機會 (section5.9)。
The codes of the two is also different.
HTTP/2 Push is a bit tricky to code, and it definitely has to go along with SSL.
https://pjchender.dev/webdev/course-fem-realtime/#http2-pushServer Sent Event implementation is simple
https://www.youtube.com/watch?v=aPrrfVs9mDc
Demo Code
Finally, I referred to these resources to write a simple Server Sent Event example. The README.md file also explains how to perform tests, and even includes instructions on how to test and call this Server Sent Event server from another Node.js Server(User fetch getReader method).
https://github.com/surferintaiwan/test-creating-server-sent-event-server
Reference: