bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Advanced Communication
Node.js•Advanced Communication

Node.js Socket.IO

Concept visual

Node.js Socket.IO

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

What is Socket.IO? Socket.IO is a powerful JavaScript library that enables real-time, bidirectional, and event-based communication between web clients and servers. It's designed to work on every platform, browser, or device, focusing equally on reliability and speed.

Key Features

Real-time bidirectional communication

  • Enables instant data transfer between clients and servers

Automatic reconnection

  • Handles disconnections and reconnections automatically

Room support

  • Easily create channels for group communication

Binary support

  • Send and receive binary data (ArrayBuffer, Blob, File, etc.)

Multiplexing

  • Handle multiple sockets with namespaces

Fallback options

Formula

- Automatically falls back to HTTP long - polling if WebSockets aren't available

Use Cases

Real-time chat applications

Live notifications

Collaborative tools

Online gaming

Live analytics

Document collaboration

Real-time dashboards

IoT applications

Socket.IO consists of two parts:

Formula

A client - side library that runs in the browser
A server - side library for Node.js

Installing Socket.IO

Server-Side Installation

Install Socket.IO in your Node.js project using npm or yarn: # Using npm npm install socket.io # Or using Yarn yarn add socket.io

Client-Side Setup

Choose one of the following methods to include the client library: Option 1: CDN (Quick Start)

Formula

< script src ="https://cdn.socket.io/4.5.0/socket.io.min.js"></script >

Option 2: NPM (Recommended for Production)

Formula

# Install the client library npm install socket.io - client
# Or using Yarn yarn add socket.io - client
Option 3: Using ES6 Modules import { io } from 'socket.io - client';

Version Compatibility

Socket.IO Version Node.js Version Browser Support v4.x v12.22.0+ Chrome 49+, Firefox 53+, Safari 10+ v3.x v10.0.0+ Chrome 49+, Firefox 53+, Safari 10+ v2.x v6.0.0+ Chrome 5+, Firefox 6+, Safari 5.1+

Note:

For production, it's recommended to use the same version on both client and server. Simple Chat Application with Socket.IO

Formula

Let's build a simple real - time chat application using Node.js and Socket.IO.

This example doesn't require any login and demonstrates the basic functionality. Create the Server (app.js) Create a new file named app.js with the following content:

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve static files app.use(express.static(path.join(__dirname, 'public')));
// Simple route app.get('/', (req, res) => {
;  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Socket.IO connection handler io.on('connection', (socket) => {
console.log('A user connected');
// Handle new messages socket.on('chat message', (msg) => {
console.log('Message received:', msg);
// Broadcast the message to all connected clients io.emit('chat message', msg);
});
// Handle disconnection socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Create the Client (public/index.html)

Create a public directory and add an index.html file with this content: <!DOCTYPE html> <html> <head>

Formula

< title > Simple Chat </title >

<style>

body {
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
}
#messages {
list-style-type: none;
margin: 0;
padding: 0;
margin-bottom: 20px;
border: 1px solid #ddd;
padding: 10px;
height: 400px;
overflow-y: auto;
}
#messages li {
padding: 8px 16px;
border-bottom: 1px solid #eee;
}
#messages li:last-child {
border-bottom: none;
}
#form {
display: flex;
margin-top: 10px;
}
#input {
flex-grow: 1;
padding: 10px;
font-size: 16px;
}
button {
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
cursor: pointer;
margin-left: 10px;
}
button:hover {
background: #45a049;
}

</style> </head> <body>

Formula

< h1 > Simple Chat </h1 >

<ul id="messages"></ul> <form id="form" action="#"> <input id="input" autocomplete="off" placeholder="Type your message..." />

Formula

< button > Send </button >

</form>

Formula

< 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');
// Handle form submission form.addEventListener('submit', (e) => {
e.preventDefault();
const message = input.value.trim();
if (message) {
// Emit the message to the server socket.emit('chat message', message);
// Clear the input input.value = '';
}
});
// Listen for incoming messages socket.on('chat message', (msg) => {
const item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
// Scroll to the bottom messages.scrollTop = messages.scrollHeight;
});

</script> </body> </html>

Run the Application

Start the server:

node app.js

Open your browser and navigate to http://localhost:3000

Formula

Open multiple browser windows to see the real - time updates

Previous

Node.js GraphQL

Next

Node.js WebSockets