bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Advanced Communication
Node.js•Advanced Communication

Node.js WebSockets

Introduction to WebSockets

WebSockets provide a persistent connection between client and server, allowing for real-time, bidirectional communication.

Formula

This is different from traditional HTTP, which follows a request - response model.

Key Benefits of WebSockets

Real-time updates

: Instantly push data to clients

Efficient

: No need for repeated HTTP requests

Bidirectional

: Both client and server can send messages

Low latency

: Messages are sent immediately

WebSockets vs HTTP

Formula

Understanding the difference between WebSockets and HTTP is crucial for building real - time applications effectively.

Feature

WebSockets

Http

Connection

Persistent, single connection

New connection per request

Communication

Formula

Bidirectional, full - duplex
Unidirectional, request - response

Overhead

Minimal after handshake

Headers with every request

Use Case

Real-time applications

Traditional web pages, APIs

Example

Chat apps, live feeds Loading web pages, form submissions

Pro Tip:

WebSockets begin with an HTTP handshake (status code 101) before upgrading to the WebSocket protocol (ws:// or wss://).

Setting Up WebSockets

  1. Install the ws Module First, create a new directory for your project and initialize it:

Formula

mkdir websocket - demo cd websocket - demo npm init - y
Then, install the ws package:

npm install ws

Note:

The ws module is a simple, fast, and thoroughly tested WebSocket client and server implementation.

Creating a WebSocket Server

Let's create a simple WebSocket server that echoes back any message it receives. Create a new file called server.js

Example: WebSocket Echo Server const WebSocket = require('ws');

Formula

// Create a WebSocket server on port 8080 const wss = new WebSocket.Server({ port: 8080 });
console.log('WebSocket server is running on ws://localhost:8080');
// Connection event handler wss.on('connection', (ws) => {
console.log('New client connected');
// Send a welcome message to the client ws.send('Welcome to the WebSocket server!');
// Message event handler ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Echo the message back to the client ws.send(`Server received: ${message}`);
});
// Close event handler ws.on('close', () => {
console.log('Client disconnected');
});
});

Understanding the Code

Previous

Node.js Socket.IO