Chapter 9: Real-time Features
Chapter 9 of 15
Chapter 9: Real-time Features
9.1 WebSocket Implementation
WebSockets enable bidirectional real-time communication between client and server.
// Backend - Socket.io
const io = require('socket.io')(server, {
cors: { origin: 'http://localhost:3000' }
});
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('join-room', (roomId) => {
socket.join(roomId);
io.to(roomId).emit('user-joined', socket.id);
});
socket.on('send-message', (data) => {
io.to(data.roomId).emit('new-message', {
...data,
senderId: socket.id,
timestamp: Date.now()
});
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
9.2 Client-Side Socket Connection
// React Socket.io client
import io from 'socket.io-client';
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
const [socket, setSocket] = useState(null);
useEffect(() => {
const newSocket = io('http://localhost:5000');
setSocket(newSocket);
newSocket.emit('join-room', roomId);
newSocket.on('new-message', (message) => {
setMessages(prev => [...prev, message]);
});
return () => newSocket.close();
}, [roomId]);
const sendMessage = (text) => {
socket.emit('send-message', { roomId, text });
};
return (
<div>
{messages.map(msg => <div key={msg.id}>{msg.text}</div>)}
<input onKeyPress={(e) => {
if (e.key === 'Enter') sendMessage(e.target.value);
}} />
</div>
);
}
9.3 Real-time Notifications
// Notification system
socket.on('notification', (notification) => {
// Show browser notification
if (Notification.permission === 'granted') {
new Notification(notification.title, {
body: notification.message,
icon: notification.icon
});
}
});