Socket IO
Getting Started with Socket.IO
Build Real-Time Web Applications Easily
What is Socket.IO?
Socket.IO is a JavaScript library that enables real-time, bidirectional, and event-based communication between web clients and servers. It works on top of WebSockets and provides fallback mechanisms when WebSockets are not supported.
Why Use Socket.IO?
- Real-time chat applications
- Live notifications and updates
- Collaborative tools (whiteboards, docs, games)
- Tracking data streams in real-time
Installation
To install Socket.IO, run the following commands:
npm install socket.io
And for the client side:
npm install socket.io-client
Basic Server Setup
// server.js
const { Server } = 'socket.io';
const http = require('http');
// Create HTTP server
const server = http.createServer();
const io = new Server(server, {
cors: {
origin: '*'
}
});
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('message', (data) => {
console.log('Message received:', data);
io.emit('message', data);
});
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
Basic Client Setup
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Client</title>
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
</head>
<body>
<h2>Simple Chat</h2>
<input id="msg" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = io('http://localhost:3000');
function sendMessage() {
const msg = document.getElementById('msg').value;
socket.emit('message', msg);
}
socket.on('message', (data) => {
const li = document.createElement('li');
li.textContent = data;
document.getElementById('messages').appendChild(li);
});
</script>
</body>
</html>
How It Works
- The server listens for client connections using
io.on('connection'). - Clients emit events like
'message'to the server. - The server can broadcast messages back to all connected clients.
Conclusion
Socket.IO simplifies real-time communication between client and server. With just a few lines of code, you can build chat apps, live dashboards, multiplayer games, and much more.