Patterns
Websockets & SSE
1. WebSockets (Full-Duplex)
Theory: WebSockets provide a persistent, two-way (bi-directional) communication channel over a single TCP connection
Bi-directional: Both the client and server can send messages at any time
. Low Latency: Once the connection is open, there is very little overhead, making it faster than repeatedly opening HTTP connections
. Use Case: Real-time collaboration tools, gaming, or the "Zoom-like" application logic you've worked on
.
The Process (using Socket.io):
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('A user connected');
// Listening for a message from the client
socket.on('chat-message', (msg) => {
// Broadcasting the message to everyone connected
io.emit('chat-message', msg);
});
});2. Server-Sent Events (SSE) (Uni-directional)
Theory: SSE is a standard that allows servers to push data to web pages over HTTP
Uni-directional: The server "streams" updates to the client
.Automatic Reconnection: Browsers handle reconnections automatically if the link drops
.Lightweight: It uses standard HTTP and doesn't require complex protocols or heavy libraries
.Use Case: Real-time dashboards, stock price updates, or news feeds
.
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Sending a message every 5 seconds
setInterval(() => {
res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);
}, 5000);
});