Server-Sent Events (Server-Sent Events, abbreviated as SSE) is a technology that allows servers to actively push data to clients (typically web browsers). Compared to traditional polling or long polling, SSE provides a more efficient and straightforward method for achieving one-way communication from server to client.
How It Works
-
Establishing the Connection: The client (e.g., browser) initiates an SSE connection by sending a standard HTTP request to the server. This is typically done by setting the
Acceptheader of the HTTP request totext/event-stream. This HTTP connection remains open and does not close after data transmission, unlike a standard HTTP request. -
Sending Data: Once the connection is established, the server can send data to the client at any time. The server pushes these messages by sending text data in a specific format. Each message ends with a pair of consecutive newline characters `
`. For example:
shelldata: Hello, world!
The server can also send multi-line data:
shelldata: first line data: second line
- Maintaining the Connection: If the connection is interrupted for any reason (e.g., network issues), the client typically automatically attempts to reconnect. The client can control the reconnection interval by including a
retryfield in the message:
shellretry: 10000 data: Please wait for 10 seconds...
- Event Identification: To better manage different types of messages, the server can send messages with event names. The client can decide how to handle these messages based on the event type:
shellevent: user-login data: {"username": "example"}
Practical Example
Suppose we are developing an online stock trading platform that requires real-time updates of stock prices. Using SSE can effectively fulfill this requirement. Whenever the stock price changes on the server side, SSE can push the latest stock price to all online clients. Upon receiving the update, the client can immediately reflect these changes on the user interface without requiring manual page refreshes by the user.
Summary
Server-Sent Events is an efficient web technology suitable for scenarios where servers need to push data to clients in real time. It is relatively simple to implement and use, as it is built on standard HTTP protocols. Additionally, since the connection is one-way, it is simpler than WebSocket, especially when only one-way data flow from server to client is required.