Today’s Offer Enroll today and get access to premium content.
App Store Google Play
Awaiting Solution

How to Use WebSockets for Real-Time Communication in Node.js?

Let's bring the best possible answer from the community.

Asked by Admin
Oct 18, 2025 23:15
Updated 12 hours, 12 minutes ago
1 Answers

Problem Overview

WebSockets provide a full-duplex communication channel over a single TCP connection, making them ideal for real-time applications like chat apps, gaming, and live notifications. Here's how to implement WebSockets in a Node.js application:

  • Step 1: Install the ws library using npm:
npm install ws
  • Step 2: Set up a basic WebSocket server:
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

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

  ws.on('message', (message) => {
    console.log('Received: %s', message);
    // Echo back the message to the client
    ws.send(`Server: ${message}`);
  });
});

console.log('WebSocket server is running on ws://localhost:8080');
  • Step 3: Connect to the WebSocket server from the client:
const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => {
  socket.send('Hello, Server!');
};

socket.onmessage = (event) => {
  console.log('Message from server:', event.data);
};

This setup will allow your Node.js application to communicate in real-time with connected clients. Remember to handle errors and disconnections appropriately to ensure a robust implementation.

Looking for the best answer Last updated Oct 18, 2025 23:15

Community Solutions (1)

Share Your Solution
AD
Admin
Oct 18, 2025 23:15 0 votes

WebSockets provide a full-duplex communication channel over a single TCP connection, making them ideal for real-time applications like chat apps, gaming, and live notifications. Here's how to implement WebSockets in a Node.js application:

  • Step 1: Install the ws library using npm:
npm install ws
  • Step 2: Set up a basic WebSocket server:
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

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

  ws.on('message', (message) => {
    console.log('Received: %s', message);
    // Echo back the message to the client
    ws.send(`Server: ${message}`);
  });
});

console.log('WebSocket server is running on ws://localhost:8080');
  • Step 3: Connect to the WebSocket server from the client:
const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => {
  socket.send('Hello, Server!');
};

socket.onmessage = (event) => {
  console.log('Message from server:', event.data);
};

This setup will allow your Node.js application to communicate in real-time with connected clients. Remember to handle errors and disconnections appropriately to ensure a robust implementation.

0 total

Want to contribute a solution?

Sign in to share your expertise and help the community solve this challenge.

Login to Answer