DEV Community

Prathviraj H
Prathviraj H

Posted on

Understanding WebSockets and the Socket.IO Library

Introduction

Traditional HTTP requests are stateless and one-way, meaning the client must request data from the server every time. But what if we need real-time communication, like in chat apps, live notifications, or stock price updates? This is where WebSockets and Socket.IO come in.

In this blog, we’ll break down what WebSockets are, how they work, and how Socket.IO simplifies WebSocket implementation.

What Are WebSockets?

WebSockets provide full-duplex communication between a client and a server over a single persistent connection. Unlike HTTP, where a client has to repeatedly send requests (polling), WebSockets keep the connection open for continuous data exchange.

How WebSockets Work

1️⃣ The client sends a WebSocket handshake request.
2️⃣ The server responds with a WebSocket handshake acceptance.
3️⃣ A persistent, bidirectional connection is established.
4️⃣ Both the client and server can now send/receive messages in real time.

/ Client-side
const socket = new WebSocket("wss://example.com/socket");

socket.onopen = () => {
    console.log("Connected to WebSocket server");
    socket.send("Hello, Server!");
};

socket.onmessage = (event) => {
    console.log("Message from server:", event.data);
};
Enter fullscreen mode Exit fullscreen mode

// Server-side (Node.js)
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 8080 });

server.on("connection", (ws) => {
    console.log("Client connected");
    ws.send("Welcome to WebSocket Server!");

    ws.on("message", (message) => {
        console.log("Received:", message);
    });
});
Enter fullscreen mode Exit fullscreen mode

Why Use Socket.IO?

WebSockets are powerful, but they have some challenges:

  • Browser compatibility issues
  • Reconnection handling
  • Fallback mechanisms for unsupported clients
  • Scalability with multiple servers

Socket.IO is a JavaScript library that simplifies WebSocket implementation by handling these issues for you.

Key Features of Socket.IO

✅ Works with WebSockets but provides fallbacks (like long polling)
✅ Automatic reconnection if the connection is lost
✅ Supports event-based communication (not just text messages)
✅ Can handle multiple servers (with load balancing)

How to Use Socket.IO

  1. Install Socket.IO
npm install socket.io
Enter fullscreen mode Exit fullscreen mode
  1. Server-Side (Node.js + Express)
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");

const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on("connection", (socket) => {
    console.log("A user connected");
    socket.emit("message", "Welcome to Socket.IO server!");

    socket.on("chat", (msg) => {
        console.log("Received chat message:", msg);
        io.emit("chat", msg); // Broadcast to all clients
    });
});

server.listen(3000, () => console.log("Server running on port 3000"));
Enter fullscreen mode Exit fullscreen mode
  1. Client-Side (React / Vanilla JS)
import { io } from "socket.io-client";

const socket = io("http://localhost:3000");

socket.on("message", (msg) => {
    console.log("Server says:", msg);
});

socket.emit("chat", "Hello, Server!");
Enter fullscreen mode Exit fullscreen mode

Conclusion

If you need real-time communication, WebSockets provide a great low-level solution, but Socket.IO makes implementation much easier with automatic reconnection, event handling, and scalability.

Top comments (0)