Socket.IO is a powerful library for real-time, bidirectional communication between clients and servers. It's widely used in web applications to enable features like live chat, collaborative editing, and real-time data updates. Let's dive into the basics!
Installation 📦
To get started, install Socket.IO via npm:
npm install socket.io
For browser use, include the CDN link:
<script src="https://cdn.socket.io/4.6.5/socket.io.min.js"></script>
Basic Usage 📡
Server Setup
Initialize Socket.IO in your Node.js server:const io = require('socket.io')(3000); io.on('connection', (socket) => { console.log('A user connected!'); });
Client Connection
Connect to the server from the client side:const socket = io('http://localhost:3000'); socket.on('connect', () => { console.log('Connected to server!'); });
Sending & Receiving Events
Useemit
to send events andon
to listen:socket.emit('message', 'Hello Server!'); // Send socket.on('message', (data) => { // Receive console.log('Received:', data); });
Example Scenario 🎉
Imagine a live chat application:
Further Learning 📚
For more advanced topics like rooms, namespaces, or authentication, check out our Socket.IO Quickstart Guide.