Socket.io Guide
Socket.ioReal-Time Communication
Build real-time bidirectional event-based communication. Perfect for chat apps, live updates, and collaborative features.
Contents
Socket.io Basics
Socket.io enables real-time bidirectional event-based communication between client and server.
bash
# Installation
npm install socket.io
# Client Installation
npm install socket.io-clientjavascript
// Server Setup
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, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
// Connection Event
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
// Client Setup
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.on('connect', () => {
console.log('Connected to server:', socket.id);
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});