0
0
Node.jsframework~5 mins

Server-Sent Events alternative in Node.js

Choose your learning style9 modes available
Introduction

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.

You want real-time chat where both client and server send messages anytime.
You need to update a dashboard live with data from the server and also send commands from client.
You want to build a multiplayer game with fast, two-way communication.
You want to push notifications from server and also receive user actions instantly.
You need a fallback when SSE is not supported or blocked by network.
Syntax
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.

Examples
This example sends a welcome message and echoes back any message received from the client.
Node.js
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}`);
  });
});
This example sends the current server time every second to connected clients.
Node.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', ws => {
  setInterval(() => {
    ws.send(`Server time: ${new Date().toLocaleTimeString()}`);
  }, 1000);
});
Sample Program

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.

Node.js
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');
  });
});
OutputSuccess
Important Notes

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.

Summary

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.