What is WebSocket, and How to Implement WebSocket in NodeJS (Part 2 of 3)

What is WebSocket, and How to Implement WebSocket in NodeJS (Part 2 of 3)

What is WebSocket, and How to Implement WebSocket in NodeJS (Part 2 of 3)
5 min read

In the previous article (Part 1), we learned what WebSocket is and how to create a basic WebSocket server using NodeJS. Now, in Part 2, we’ll move further to explore two-way communication between client and server and how to handle messages and events effectively.


Establishing Two-Way Communication

WebSocket enables continuous data exchange between client and server without repeated HTTP requests. Once connected, both sides can send and receive data anytime.

Client-Side Example (JavaScript in Browser)

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

socket.addEventListener("open", () => {
  console.log("Connected to WebSocket server");
  socket.send("Hello from the client!");
});

socket.addEventListener("message", (event) => {
  console.log("Message from server:", event.data);
});

Server-Side Example (NodeJS)

const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 8080 });

server.on("connection", (socket) => {
  console.log("Client connected");

  socket.on("message", (message) => {
    console.log("Message from client:", message);
    socket.send("Message received by server");
  });

  socket.on("close", () => {
    console.log("Client disconnected");
  });
});

With this setup, your system now supports bi-directional messaging, allowing clients and servers to communicate freely.


Handling Multiple Clients

For real-world applications such as chat systems, live dashboards, or notification services, multiple clients will connect simultaneously. Here’s how you can broadcast messages to all connected clients:

server.on("connection", (socket) => {
  console.log("New client connected");

  socket.on("message", (message) => {
    server.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});

This example broadcasts any message received from one client to all connected clients.


Error Handling and Message Validation

To ensure stability, always validate incoming messages and handle errors properly:

socket.on("message", (message) => {
  try {
    const data = JSON.parse(message);
    console.log("Data:", data);
  } catch (error) {
    socket.send("Invalid message format. Please use JSON.");
  }
});

Interim Summary

In this second part, we have covered:

  1. How to connect clients and servers via WebSocket.

  2. Building two-way communication.

  3. Broadcasting messages to multiple clients.

  4. Handling errors and invalid messages.

In Part 3, we will dive into advanced implementations — adding authentication, integrating WebSocket with Express, and optimizing performance for large-scale applications.

Recommended for you