Socket.io can be used for building collaborative applications where multiple users can work on the same document or project simultaneously. Examples include collaborative text editors, design tools, or project management apps.
Example: Collaborative Text Editor
Server-side:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
let documentContent = '';
io.on('connection', (socket) => {
console.log('A user connected');
// Send the current document content to the new client
socket.emit('document', documentContent);
// Listen for changes from clients and broadcast them
socket.on('update document', (content) => {
documentContent = content;
socket.broadcast.emit('document', content);
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
Client-side:
<!DOCTYPE html>
<html>
<head>
<title>Collaborative Editor</title>
<script src="/socket.io/socket.io.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const socket = io();
const editor = document.getElementById('editor');
// Receive the document content from the server
socket.on('document', (content) => {
editor.value = content;
});
// Send updates to the server
editor.addEventListener('input', () => {
socket.emit('update document', editor.value);
});
});
</script>
</head>
<body>
<textarea id="editor" style="width: 100%; height: 300px;"></textarea>
</body>
</html>
Leave a Reply