I recently built a large language model chat interface, but traditional request methods only transfer data to the frontend after the model completes its entire output, causing users to think the interface or API has frozen.
Additionally, due to stateless microservices, using WebSockets for long connections requires handling reconnect logic, which introduces extra complexity. SSE supports reconnection after disconnection by default, is based on the HTTP protocol, and is lightweight and simple for transmitting text data.
I also encountered some pitfalls during implementation; please read the code comments below.
JAVA
Issues encountered:
- Nginx caches messages, preventing them from streaming. Nginx caching needs to be disabled to enable direct streaming.
new SseEmitter()disconnects after 30 seconds by default, sonew SseEmitter(0L)needs to be specified to allow unlimited message push duration.- SSE can only transmit single-line data and cannot recognize spaces and line breaks, so spaces and carriage returns need to be replaced with placeholders.
1 |
|
Frontend
Issues encountered:
- Since EventSource only supports the GET method, values can be passed via fields when establishing a connection.
- SSE can only transmit single-line data and cannot recognize spaces and line breaks, so spaces and carriage returns need to be replaced with placeholders.
- It is recommended to accumulate received data and continuously parse the full data into HTML to achieve real-time parsing like ChatGPT, improving the user experience.
1 | // 由于EventSource只支持get方式,可以建立连接时通过字段传值 |