Quick reference for all Socket.IO events in the chat system.
Join a conversation room to receive real-time messages.
Payload:
{
conversationId: string; // e.g., "user123_user456"
userId: string; // Current user ID
}Example:
socket.emit('join_conversation', {
conversationId: 'user123_user456',
userId: 'user123'
});Send a new message in a conversation.
Payload:
{
conversationId: string;
receiverId: string;
messageType: 'text' | 'image' | 'file';
content: {
text?: string; // For text messages
fileUrl?: string; // For image/file messages
fileName?: string; // Original file name
fileSize?: number; // File size in bytes
};
}Examples:
Text message:
socket.emit('send_message', {
conversationId: 'user123_user456',
receiverId: 'user456',
messageType: 'text',
content: { text: 'Hello!' }
});Image message:
socket.emit('send_message', {
conversationId: 'user123_user456',
receiverId: 'user456',
messageType: 'image',
content: {
fileUrl: '/uploads/chat/image123.jpg',
fileName: 'photo.jpg',
fileSize: 245678
}
});Mark messages as read.
Payload:
{
conversationId: string;
messageIds: string[]; // Array of message IDs
}Example:
socket.emit('mark_as_read', {
conversationId: 'user123_user456',
messageIds: ['msg1', 'msg2', 'msg3']
});Notify that user started typing.
Payload:
{
conversationId: string;
}Example:
socket.emit('typing_start', {
conversationId: 'user123_user456'
});Notify that user stopped typing.
Payload:
{
conversationId: string;
}Example:
socket.emit('typing_stop', {
conversationId: 'user123_user456'
});Check if a user is online.
Payload:
{
userId: string;
}Example:
socket.emit('get_online_status', {
userId: 'user456'
});Leave a conversation room.
Payload:
{
conversationId: string;
}Example:
socket.emit('leave_conversation', {
conversationId: 'user123_user456'
});Emitted when socket successfully connects.
Payload: None
Example:
socket.on('connect', () => {
console.log('Connected!', socket.id);
});Emitted after successful authentication (optional).
Payload:
{
userId: string;
success: boolean;
}Example:
socket.on('authenticated', (data) => {
console.log('Authenticated:', data.userId);
});Confirmation that user joined a conversation.
Payload:
{
conversationId: string;
}Example:
socket.on('joined_conversation', (data) => {
console.log('Joined conversation:', data.conversationId);
});Receive a new message in a conversation.
Payload:
{
_id: string;
conversationId: string;
senderId: {
_id: string;
name: string;
avatar?: string;
};
receiverId: string;
messageType: 'text' | 'image' | 'file';
content: {
text?: string;
fileUrl?: string;
fileName?: string;
fileSize?: number;
};
status: 'sent' | 'delivered' | 'read';
timestamp: Date;
}Example:
socket.on('new_message', (message) => {
console.log('New message:', message);
// Add message to your UI
addMessageToChat(message);
});Confirmation that message was delivered.
Payload:
{
messageId: string;
}Example:
socket.on('message_delivered', (data) => {
console.log('Message delivered:', data.messageId);
// Update message status in UI
updateMessageStatus(data.messageId, 'delivered');
});Notification that messages were read.
Payload:
{
messageIds: string[];
readBy: string; // User ID who read the messages
}Example:
socket.on('message_read', (data) => {
console.log('Messages read by:', data.readBy);
// Update message status in UI
data.messageIds.forEach(id => {
updateMessageStatus(id, 'read');
});
});Notification that a user is typing.
Payload:
{
conversationId: string;
userId: string;
isTyping: boolean;
}Example:
socket.on('user_typing', (data) => {
if (data.isTyping) {
showTypingIndicator(data.userId);
} else {
hideTypingIndicator(data.userId);
}
});User online/offline status update.
Payload:
{
userId: string;
isOnline: boolean;
lastSeen: Date | null;
}Example:
socket.on('user_online_status', (data) => {
console.log(`User ${data.userId} is ${data.isOnline ? 'online' : 'offline'}`);
updateUserStatus(data.userId, data.isOnline, data.lastSeen);
});Error notification.
Payload:
{
message: string;
code?: string;
}Example:
socket.on('error', (error) => {
console.error('Socket error:', error.message);
showErrorNotification(error.message);
});Emitted when socket disconnects.
Payload: Reason string
Example:
socket.on('disconnect', (reason) => {
console.log('Disconnected:', reason);
if (reason === 'io server disconnect') {
// Server disconnected, try to reconnect
socket.connect();
}
});import { io } from 'socket.io-client';
// Connect with authentication
const socket = io('http://localhost:4000', {
auth: { token: 'your_jwt_token' }
});
// Connection events
socket.on('connect', () => {
console.log('β
Connected');
// Join conversation
socket.emit('join_conversation', {
conversationId: 'user123_user456',
userId: 'user123'
});
});
socket.on('disconnect', (reason) => {
console.log('β Disconnected:', reason);
});
// Message events
socket.on('new_message', (message) => {
console.log('π© New message:', message);
displayMessage(message);
});
socket.on('message_delivered', ({ messageId }) => {
console.log('β
Delivered:', messageId);
updateMessageStatus(messageId, 'delivered');
});
socket.on('message_read', ({ messageIds, readBy }) => {
console.log('ποΈ Read by:', readBy);
messageIds.forEach(id => updateMessageStatus(id, 'read'));
});
// Typing events
socket.on('user_typing', ({ userId, isTyping }) => {
if (isTyping) {
showTypingIndicator(userId);
} else {
hideTypingIndicator(userId);
}
});
// Status events
socket.on('user_online_status', ({ userId, isOnline, lastSeen }) => {
updateUserStatus(userId, isOnline, lastSeen);
});
// Error handling
socket.on('error', (error) => {
console.error('β Error:', error);
showErrorNotification(error.message);
});
// Send message
function sendMessage(conversationId, receiverId, text) {
socket.emit('send_message', {
conversationId,
receiverId,
messageType: 'text',
content: { text }
});
}
// Typing indicators
let typingTimeout;
function handleTyping(conversationId) {
socket.emit('typing_start', { conversationId });
clearTimeout(typingTimeout);
typingTimeout = setTimeout(() => {
socket.emit('typing_stop', { conversationId });
}, 3000);
}
// Mark as read
function markAsRead(conversationId, messageIds) {
socket.emit('mark_as_read', {
conversationId,
messageIds
});
}Client A Server Client B
| | |
|--send_message----------->| |
| |--new_message------------>|
|<-message_delivered-------| |
| | |
Client A Server Client B
| | |
|--typing_start----------->| |
| |--user_typing------------>|
| | (isTyping: true) |
| | |
|--typing_stop------------>| |
| |--user_typing------------>|
| | (isTyping: false) |
Client A Server Client B
| | |
| |<-mark_as_read-----------|
|<-message_read------------| |
| (update UI) | |
Use this simple HTML file to test events:
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Chat Test</title>
<script src="https://cdn.socket.io/4.7.0/socket.io.min.js"></script>
</head>
<body>
<h1>Socket.IO Chat Test</h1>
<div id="status">Disconnected</div>
<div id="messages"></div>
<input id="token" placeholder="JWT Token" />
<button onclick="connect()">Connect</button>
<input id="conversationId" placeholder="Conversation ID" />
<button onclick="joinConversation()">Join</button>
<input id="receiverId" placeholder="Receiver ID" />
<input id="messageText" placeholder="Message" />
<button onclick="sendMessage()">Send</button>
<script>
let socket;
function connect() {
const token = document.getElementById('token').value;
socket = io('http://localhost:4000', {
auth: { token }
});
socket.on('connect', () => {
document.getElementById('status').textContent = 'Connected';
console.log('Connected!');
});
socket.on('new_message', (message) => {
const div = document.createElement('div');
div.textContent = JSON.stringify(message);
document.getElementById('messages').appendChild(div);
});
socket.on('error', (error) => {
alert('Error: ' + error.message);
});
}
function joinConversation() {
const conversationId = document.getElementById('conversationId').value;
socket.emit('join_conversation', {
conversationId,
userId: 'test_user'
});
}
function sendMessage() {
const conversationId = document.getElementById('conversationId').value;
const receiverId = document.getElementById('receiverId').value;
const text = document.getElementById('messageText').value;
socket.emit('send_message', {
conversationId,
receiverId,
messageType: 'text',
content: { text }
});
}
</script>
</body>
</html>Save as test-chat.html and open in browser!