Introduction to Socket.IO

Sushil ChaubeySushil Chaubey
2 min read

Socket.IO is a JavaScript library that enables real-time, bidirectional, and event-based communication between the browser and the server. It's built on top of WebSockets but provides fallbacks for older browsers, making it reliable and robust.

It’s widely used in:

  • Chat applications

  • Real-time notifications

  • Live dashboards

  • Multiplayer games


⚙️ How It Works

Socket.IO has two parts:

  • A server-side library for Node.js (socket.io)

  • A client-side library that runs in the browser (socket.io-client)

They communicate over WebSockets or fallback transports (like long polling) to maintain a live connection.


🧪 Example: Real-Time Chat (Basic)

1. Server-side (Node.js)

javascriptCopyEdit// server.js
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);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('A user connected');

  socket.on('chat message', (msg) => {
    io.emit('chat message', msg); // Broadcast to all clients
  });

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

server.listen(3000, () => {
  console.log('Listening on *:3000');
});

2. Client-side (HTML + JS)

htmlCopyEdit<!-- index.html -->
<!DOCTYPE html>
<html>
  <head><title>Chat App</title></head>
  <body>
    <ul id="messages"></ul>
    <form id="form">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();

      const form = document.getElementById('form');
      const input = document.getElementById('input');
      const messages = document.getElementById('messages');

      form.addEventListener('submit', (e) => {
        e.preventDefault();
        if (input.value) {
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });

      socket.on('chat message', (msg) => {
        const item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
      });
    </script>
  </body>
</html>

🚀 Running It

  1. Run npm init -y and install dependencies:

     npm install express socket.io
    
  2. Save both files, then run:

     node server.js
    
  3. Open http://localhost:3000 in multiple tabs to test real-time chatting.

0
Subscribe to my newsletter

Read articles from Sushil Chaubey directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sushil Chaubey
Sushil Chaubey