Basic, Intro
Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers.
Websockets connections can both send data to the browser and receive data from the browser.
SSE connections can only push data to the browser.
SSE is Simpler, case by case.
Backend
SseEmitter (Spring Framework 6.0.2 API)
1 | /** |
- SseEmitter: one implement of sse
- ScheduledExecutorService.scheduleWithFixedDelay: sent data with schedule delay, like use
Scheduled
annotation for a job, but job is not recomend
Frontend, with token for authorization
https://github.com/Yaffle/EventSource
1 | const createEventSource = url => { |
nginx
It’s important to note that an EventSource requires an HTTP/1.1 server to work correctly. This is because, unlike XMLHttpRequest, an EventSource request is kept open indefinitely and therefore relies on features only present in HTTP/1.1, such as chunked encoding. In addition, the HTTP status code of the response must be 200 OK, or the connection will be closed.
1 | worker_processes 4; |
Problems
1.timeout, responsebodyemitter has already completed
- if sent data so many, set timeout to zero, but if unnecessary like send data one time, should use default timeout which is not set then, or set some timeout like
new SseEmitter(1000L)
which means 1s timeout
2.frontend error happen
- frontend usecase is simple, mostly the error is some backend error
Reference
- HTTP version should 1.1
- server-sent_events.html
- java source code of SseEmitterController
- sse-with-timeout
- Server-Sent Events Using Spring - DZone Java
- Spring Server Sent Events - ResponseBodyEmitter is already set complete
- Zero to Hero in Server Sent Events.
- Quarkus-For-Spring-Developers-Red-Hat
- 本文作者: Linking
- 本文链接: https://linking.fun/2022/11/28/server-sent-events/
- 版权声明: 版权所有,转载请注明出处!