Server-Sent Events (SSE) let a server send updates to a web page automatically. Sometimes, you need another way to do this, like WebSockets, which allow two-way communication between client and server.
Server-Sent Events alternative in Node.js
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function message(data) { console.log('received: %s', data); }); ws.send('Hello! Message from server.'); });
This example shows a simple WebSocket server in Node.js.
WebSocket allows messages to be sent both ways anytime, unlike SSE which is one-way from server to client.
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { ws.send('Welcome client!'); ws.on('message', message => { console.log(`Received: ${message}`); ws.send(`You said: ${message}`); }); });
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { setInterval(() => { ws.send(`Server time: ${new Date().toLocaleTimeString()}`); }, 1000); });
This complete WebSocket server listens on port 8080. When a client connects, it sends a greeting. It listens for messages from the client and replies back with confirmation. It also logs connection and disconnection events.
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { console.log('Client connected'); ws.send('Hello! You are connected to WebSocket server.'); ws.on('message', message => { console.log(`Received from client: ${message}`); ws.send(`Server received: ${message}`); }); ws.on('close', () => { console.log('Client disconnected'); }); });
WebSockets require both client and server support.
They work well for two-way real-time communication, unlike SSE which is one-way.
Use secure WebSocket (wss://) in production for encryption.
Server-Sent Events send updates only from server to client.
WebSockets allow two-way communication, making them a good alternative.
Use WebSockets when you need real-time, interactive communication.