🎯 What You'll Learn
In this lesson, you'll build a complete private messaging system:
- How to send private messages between users
- User lookup and recipient targeting
- Message delivery confirmation
- Error handling for offline users
🔑 Private Messaging Concepts
- Direct Messaging: Messages sent from one user to another
- User Lookup: Finding recipients by username
- Message Routing: Sending messages to specific socket connections
- Delivery Confirmation: Confirming messages were sent successfully
👤 User Registration
Register with a username to start private messaging:
💬 Private Chat Interface
Select a user from the list and start a private conversation
👥 Online Users
No users online
📤 Sending Private Messages
Learn how to send messages to specific users:
// Client-side: Send a private message
socket.emit('private message', {
to: 'recipientUsername',
message: 'Hello! This is a private message.'
});
// Server-side: Handle private messaging
socket.on('private message', (data) => {
const { to, message } = data;
const sender = users[socket.id];
if (!sender) {
socket.emit('error', { message: 'Please register first!' });
return;
}
// Find recipient by username
const recipient = Object.values(users).find(user => user.username === to);
if (recipient) {
// Send to recipient
io.to(recipient.id).emit('private message', {
from: sender.username,
message: message,
timestamp: new Date().toISOString()
});
// Send confirmation to sender
socket.emit('private message sent', {
to: to,
message: message,
timestamp: new Date().toISOString()
});
} else {
socket.emit('error', { message: `User ${to} not found or not online` });
}
});
Private Messaging Demo
Try these scenarios:
- Register with different usernames in multiple tabs
- Select a recipient from the dropdown
- Send private messages between users
- Try sending to a non-existent user
📥 Receiving Private Messages
Understanding how to handle incoming private messages:
// Client-side: Listen for private messages
socket.on('private message', (data) => {
const { from, message, timestamp } = data;
console.log(`Private message from ${from}: ${message}`);
// Display the message in your chat interface
displayPrivateMessage(from, message, timestamp, 'received');
});
// Client-side: Listen for message confirmation
socket.on('private message sent', (data) => {
const { to, message, timestamp } = data;
console.log(`Message sent to ${to}: ${message}`);
// Display the message in your chat interface
displayPrivateMessage(to, message, timestamp, 'sent');
});
// Client-side: Handle errors
socket.on('error', (data) => {
console.error('Error:', data.message);
// Display error message to user
});
💡 Private Messaging Best Practices
- User Validation: Always check if sender is registered
- Recipient Lookup: Find users by username, not socket ID
- Error Handling: Provide clear feedback for failed messages
- Message Confirmation: Confirm successful message delivery
- Security: Validate message content and sender permissions
🔍 Message Routing Logic
Understanding how messages are routed to specific users:
// Server-side: Message routing process
socket.on('private message', (data) => {
const { to, message } = data;
const sender = users[socket.id];
// Step 1: Validate sender
if (!sender) {
socket.emit('error', { message: 'Please register first!' });
return;
}
// Step 2: Find recipient
const recipient = Object.values(users).find(user => user.username === to);
// Step 3: Check if recipient exists and is online
if (!recipient) {
socket.emit('error', { message: `User ${to} not found or not online` });
return;
}
// Step 4: Send message to recipient
io.to(recipient.id).emit('private message', {
from: sender.username,
message: message,
timestamp: new Date().toISOString()
});
// Step 5: Confirm delivery to sender
socket.emit('private message sent', {
to: to,
message: message,
timestamp: new Date().toISOString()
});
});
🎯 Practice Exercise
Test the private messaging system:
Private Chat Test
Try these scenarios:
- Open multiple browser tabs and register different users
- Send private messages between users
- Try sending to a user that doesn't exist
- Close a tab and try sending to that user
- Observe message delivery confirmations
✅ What You've Learned
- ✅ How to send private messages between users
- ✅ User lookup and recipient targeting
- ✅ Message delivery confirmation
- ✅ Error handling for offline users
- ✅ Building a complete private chat interface