Server-Sent Events (SSE) and WebSocket are technologies used to enable real-time communication between servers and clients, but they are significantly different in design goals, protocol features, and applicable scenarios. Here is a detailed comparison of the two:
1. Summary of core differences
Contrast dimensions | SSE (Server-Sent Events) | WebSocket |
---|---|---|
Communication direction | One-way (server → client) | Full Duplex (Server ↔ Client) |
Protocol basis | Based on HTTP | Independent Agreement (ws:// orwss:// ) |
Data format | Plain text (event stream format) | Binary or text |
Automatic reconnection | Built-in support | Need to be manually implemented |
Browser compatibility | Mainstream browser support except IE | All modern browsers support |
Applicable scenarios | The server pushes real-time data to the client (such as stock quotes, news) | Two-way interactive scenarios (such as chat, games, collaborative editing) |
2. Comparison of technical details
1. Connection establishment
-
SSE:
// Client code const eventSource = new EventSource("/sse-endpoint"); = (e) => ();
- Using standard HTTP requests, the header contains:
Accept: text/event-stream Cache-Control: no-cache Connection: keep-alive
- Using standard HTTP requests, the header contains:
-
WebSocket:
// Client code const socket = new WebSocket("ws:///ws"); = (e) => ();
- Switch protocols via HTTP Upgrade:
GET /ws HTTP/1.1 Upgrade: websocket Connection: Upgrade
- Switch protocols via HTTP Upgrade:
2. Data transmission
-
SSE:
- Server response format:
event: priceUpdate data: {"symbol":"AAPL","price":182.73} \n\n
- Support event types (
event
Field) and retry time (retry
Field)
- Server response format:
-
WebSocket:
- Free transmission of binary or text frames:
// Send text ("Hello Server!"); // Send binary data (such as files) (arrayBuffer);
- Free transmission of binary or text frames:
3. Connection maintenance
characteristic | SSE | WebSocket |
---|---|---|
Heartbeat detection | Rely on HTTP long connections | Ping/Pong frame needs to be manually implemented |
Disconnection of wires | Automatic (the client defaults to retry in 3 seconds) | Need to reconnect manually |
Connection status management | Simple (HTTP status code control) | Complex (requires multiple frame types) |
3. Choose suggestions
Scenarios using SSE ✅
-
One-way push of the server
- Real-time monitoring (server metrics, log flow)
- News/Stock Quotes Push
- Long polling alternatives
-
Need to be simple to implement
- Reuse HTTP infrastructure without additional protocols
- Automatic reconnection and event ID support
-
Mainly text data
- Structured Data (JSON) Transmission
Scenarios using WebSocket ✅
-
Two-way interaction requirements
- Online Chat Room
- Multiplayer online game
- Real-time collaborative editing
-
Low latency communication
- High-frequency bidirectional data exchange (such as video conferencing signaling)
-
Binary data transmission
- File transfer, audio and video streaming
4. Comparison of code examples
SSE implementation (Spring Boot)
@GetMapping("/sse")
public SseEmitter streamData() {
SseEmitter emitter = new SseEmitter();
(() -> {
try {
for (int i = 0; i < 10; i++) {
(
()
.name("update")
.data("Event #" + i)
);
(1000);
}
();
} catch (Exception e) {
(e);
}
});
return emitter;
}
WebSocket implementation (Spring Boot)
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
(myHandler(), "/ws")
.setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myHandler() {
return new TextWebSocketHandler() {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
// Process client messages
(new TextMessage("ECHO: " + ()));
}
};
}
}
V. Performance and resource consumption
index | SSE | WebSocket |
---|---|---|
Connection overhead | Higher (HTTP header duplicate transmission) | Low (no extra overhead after connection) |
Server memory usage | Independent thread/connection per connection | More efficient connection management |
Suitable connection number | Suitable for medium and low concurrency (thousands of connections) | Suitable for high concurrency (ten thousand connections) |
6. Compatibility Solution
When compatibility with old browsers is required:
- SSE downgrade plan: Use Long Polling
-
WebSocket downgrade plan: Use SockJS library
const sock = new SockJS('/ws-endpoint'); = (e) => ();
Summarize
- SSEyesSimple, one-wayIdeal for real-time communication, especially suitable for projects with existing HTTP architectures.
- WebSocketIf neededTwo-way, low latencyInteraction is indispensable, but the implementation is more complex.
Select according to your application scenario:
- Just receive server updates?→ Use SSE
- Need two-way dialogue?→ Use WebSocket