Real-Time Communication with Node.js and WebSockets

Node.js Logo

WebSockets provide a full-duplex communication channel over a single, long-lived TCP connection. This is perfect for real-time applications like chat apps, live notifications, and online gaming. This tutorial shows how to build a simple WebSocket server and client using the popular `ws` library.

Setting Up

npm install ws

WebSocket Server (`server.js`)

This server will listen for connections and echo back any message it receives.

const WebSocket = require('ws');

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

console.log('WebSocket server started on port 8080');

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

  ws.on('message', message => {
    console.log(`Received message => ${message}`);
    // Echo the message back to the client
    ws.send(`Hello, you sent => ${message}`);
  });

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

WebSocket Client (`client.js`)

This client will connect to the server, send a message, and log the response.

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8080');

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

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

ws.on('close', () => {
  console.log('Disconnected from server');
});

Comments