Перейти к содержимому
Skip to content
← All articles

Server-Sent Events vs WebSockets: Choosing Real-Time Communication

The Need for Real-Time Communication

Traditional HTTP follows a request-response model: the client asks, the server answers. But modern web applications need real-time updates — live dashboards, chat messages, notifications, stock tickers, monitoring alerts. Two technologies solve this: Server-Sent Events (SSE) and WebSockets. Choosing the right one depends on your use case.

Server-Sent Events (SSE)

SSE is a simple, HTTP-based protocol for streaming updates from server to client. The client opens a standard HTTP connection, and the server sends events as they occur. The connection stays open, and the browser automatically reconnects if it drops.

// Client: JavaScript EventSource API
const source = new EventSource('/api/events');

source.onmessage = (event) => {
    const data = JSON.parse(event.data);
    updateDashboard(data);
};

source.onerror = (error) => {
    console.log('SSE connection error, reconnecting...');
};

// Listen for specific event types
source.addEventListener('alert', (event) => {
    showNotification(JSON.parse(event.data));
});
// Server: PHP SSE endpoint
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // Disable nginx buffering

while (true) {
    $data = getLatestUpdates();
    if ($data) {
        echo "event: update\n";
        echo "data: " . json_encode($data) . "\n\n";
    }
    ob_flush();
    flush();
    sleep(1);
}

SSE features:

WebSockets

WebSockets provide full-duplex communication over a single TCP connection. After an HTTP upgrade handshake, both client and server can send messages at any time. The protocol supports both text and binary data.

// Client: WebSocket API
const ws = new WebSocket('wss://example.com/ws');

ws.onopen = () => {
    ws.send(JSON.stringify({ type: 'subscribe', channel: 'alerts' }));
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    handleMessage(data);
};

ws.onclose = (event) => {
    console.log('WebSocket closed:', event.code, event.reason);
    // Manual reconnection needed
    setTimeout(() => reconnect(), 3000);
};
// Server: Node.js WebSocket (ws library)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
    ws.on('message', (message) => {
        const data = JSON.parse(message);
        if (data.type === 'subscribe') {
            subscribeToChannel(ws, data.channel);
        }
    });

    // Send updates
    setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({ type: 'ping', time: Date.now() }));
        }
    }, 30000);
});

WebSocket features:

Comparison

FeatureSSEWebSockets
DirectionServer → ClientBidirectional
ProtocolHTTP/1.1, HTTP/2WS/WSS (upgrade from HTTP)
Data formatText (UTF-8)Text + Binary
ReconnectionAutomatic (built-in)Manual
Browser supportAll modern (no IE)All modern (including IE 10+)
Max connections6 per domain (HTTP/1.1)No HTTP limit
Proxy/CDN supportExcellent (standard HTTP)Requires configuration
ComplexitySimpleMore complex
ScalabilityEasier (stateless HTTP)Harder (stateful connections)

When to Use SSE

When to Use WebSockets

Performance Considerations

Implementation Tips

Conclusion

SSE and WebSockets serve different needs. SSE is the right choice for server-to-client streaming — it is simpler, works with standard HTTP infrastructure, and handles reconnection automatically. WebSockets are necessary when you need bidirectional communication or binary data. For most web monitoring and notification use cases, SSE is the pragmatic choice. Use WebSockets when bidirectional communication is a genuine requirement, not just a perceived one.

Check your website right now

Check now →
More articles: HTTP
HTTP
HTTP Methods Explained: GET, POST, PUT, DELETE and Beyond
16.03.2026 · 14 views
HTTP
Analyzing Server Response Headers: What They Reveal About a Website
11.03.2026 · 12 views
HTTP
HTTP Caching Guide: Cache-Control, ETag, Expires
14.03.2026 · 9 views
HTTP
HTTP/2 vs HTTP/3: What's New and Why Upgrade
14.03.2026 · 11 views