Loading lesson path
Concept visual
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.
Formula
- Automatically falls back to HTTP long - polling if WebSockets aren't availableSocket.IO consists of two parts:
Formula
A client - side library that runs in the browser
A server - side library for Node.jsInstalling Socket.IO
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
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';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+
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>
node app.js
Formula
Open multiple browser windows to see the real - time updates