codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

28 / 63 topics
27Real-Time Applications28WebSockets29Building a Chat Application
Tutorials/Node.js/WebSockets
🟢Node.js

WebSockets

Updated 2026-04-20
3 min read

Introduction

WebSockets provide a full-duplex communication channel over a single, long-lived connection. This makes them ideal for real-time applications such as chat apps, live notifications, and collaborative tools. In this section, we will explore how to implement WebSockets in Node.js using the popular ws library.

Setting Up Your Environment

Before diving into WebSocket implementation, ensure you have Node.js installed on your machine. You can download it from nodejs.org.

Create a new directory for your project and initialize it with npm:

mkdir websocket-example
cd websocket-example
npm init -y

Install the ws library, which is a simple to use WebSocket implementation for Node.js:

npm install ws

Basic WebSocket Server

Let's start by creating a basic WebSocket server. Create a file named server.js and add the following code:

const WebSocket = require('ws');

// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');

  ws.on('message', (message) => {
    console.log(`Received message => ${message}`);
    // Broadcast the received message to all clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

console.log('WebSocket server is running on ws://localhost:8080');

Explanation

  • WebSocket Server Initialization: We create a WebSocket server listening on port 8080.
  • Connection Event: When a client connects, we log the connection and set up event listeners for incoming messages and disconnections.
  • Message Event: When a message is received from a client, it logs the message and broadcasts it to all connected clients.
  • Close Event: Logs when a client disconnects.

Basic WebSocket Client

To test our server, let's create a simple WebSocket client. Create a file named client.js:

const WebSocket = require('ws');

// Connect to the WebSocket server
const ws = new WebSocket('ws://localhost:8080');

ws.on('open', () => {
  console.log('Connected to server');
  // Send a message to the server
  ws.send('Hello, Server!');
});

ws.on('message', (message) => {
  console.log(`Received from server => ${message}`);
});

Explanation

  • WebSocket Client Initialization: Connects to the WebSocket server running on ws://localhost:8080.
  • Open Event: Logs when the connection is established and sends a message to the server.
  • Message Event: Logs any messages received from the server.

Running the Application

Start your WebSocket server by running:

node server.js

In another terminal, start the client:

node client.js

You should see logs indicating that the client connected, sent a message to the server, and received the same message back. This demonstrates basic communication using WebSockets.

Advanced Features

Authentication

For real-world applications, you might need to authenticate users before allowing them to connect. Here's how you can implement basic authentication:

Modify server.js to include an authentication check:

wss.on('connection', (ws) => {
  console.log('Client connected');

  ws.on('message', (message) => {
    if (message === 'auth:secret') {
      ws.authenticated = true;
      ws.send('Authentication successful');
    } else if (ws.authenticated) {
      // Broadcast the received message to all authenticated clients
      wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN && client.authenticated) {
          client.send(message);
        }
      });
    } else {
      ws.send('Authentication required');
    }
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

Error Handling

It's crucial to handle errors gracefully. Add error handling in both the server and client:

Server-side error handling:

wss.on('error', (err) => {
  console.error(`WebSocket server error: ${err}`);
});

ws.on('error', (err) => {
  console.error(`Client WebSocket error: ${err}`);
});

Client-side error handling:

ws.on('error', (err) => {
  console.error(`WebSocket client error: ${err}`);
});

Heartbeats

To keep the connection alive and detect disconnections, implement heartbeats:

Server-side heartbeat:

function heartbeat() {
  this.isAlive = true;
}

wss.on('connection', (ws) => {
  ws.isAlive = true;
  ws.on('pong', heartbeat);

  ws.send(JSON.stringify({ type: 'heartbeat' }));

  const interval = setInterval(() => {
    if (ws.isAlive === false) return ws.terminate();

    ws.isAlive = false;
    ws.ping();
  }, 30000);

  ws.on('close', () => clearInterval(interval));
});

Client-side heartbeat:

ws.on('message', (data) => {
  const message = JSON.parse(data);
  if (message.type === 'heartbeat') {
    ws.send(JSON.stringify({ type: 'heartbeat' }));
  }
});

ws.on('open', () => {
  setInterval(() => {
    ws.send(JSON.stringify({ type: 'heartbeat' }));
  }, 30000);
});

Binary Data

WebSockets can also handle binary data. Here's how you can send and receive binary data:

Server-side binary handling:

ws.on('message', (data) => {
  if (Buffer.isBuffer(data)) {
    console.log('Received binary data');
    // Process the binary data
  }
});

Client-side binary sending:

const buffer = Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]); // 'hello' in ASCII
ws.send(buffer);

Best Practices

  1. Use Secure Connections: Always use wss:// (WebSocket Secure) instead of ws:// for secure communication.
  2. Handle Errors Gracefully: Implement robust error handling to manage unexpected issues.
  3. Keep Connections Alive: Use heartbeats or other mechanisms to keep connections alive and detect disconnections.
  4. Limit Message Size: Be mindful of the maximum message size and handle large messages appropriately.
  5. Authenticate Users: Ensure that only authenticated users can connect to your WebSocket server.

Conclusion

WebSockets provide a powerful way to enable real-time communication in web applications. By using Node.js and libraries like ws, you can build robust, scalable WebSocket servers and clients. This guide has covered the basics of setting up a WebSocket server and client, as well as advanced features such as authentication, error handling, heartbeats, and binary data processing. Implementing these best practices will help you create efficient and reliable real-time applications.

Feel free to explore more advanced topics like using WebSockets with frameworks like Express or integrating them into larger applications.


PreviousReal-Time ApplicationsNext Building a Chat Application

Recommended Gear

Real-Time ApplicationsBuilding a Chat Application