Real-time communication patterns with WebSockets including rooms, broadcasting, and reconnection
# WebSocket Real-Time Communication for Google Antigravity
Build real-time applications with WebSockets using Google Antigravity's Gemini 3 engine. This guide covers connection management, rooms, broadcasting, and reconnection strategies.
## WebSocket Server with Socket.io
```typescript
// src/socket/server.ts
import { Server as HttpServer } from 'http';
import { Server, Socket } from 'socket.io';
import { verifyToken } from '../auth';
import { redis } from '../redis';
interface ServerToClientEvents {
message: (data: Message) => void;
userJoined: (user: UserInfo) => void;
userLeft: (userId: string) => void;
typing: (data: { userId: string; isTyping: boolean }) => void;
error: (error: { code: string; message: string }) => void;
}
interface ClientToServerEvents {
joinRoom: (roomId: string) => void;
leaveRoom: (roomId: string) => void;
sendMessage: (data: { roomId: string; content: string }) => void;
typing: (data: { roomId: string; isTyping: boolean }) => void;
}
interface InterServerEvents {
ping: () => void;
}
interface SocketData {
userId: string;
email: string;
name: string;
}
export function createSocketServer(httpServer: HttpServer) {
const io = new Server<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>(httpServer, {
cors: {
origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
credentials: true,
},
pingTimeout: 60000,
pingInterval: 25000,
});
// Authentication middleware
io.use(async (socket, next) => {
const token = socket.handshake.auth.token;
if (!token) {
return next(new Error('Authentication required'));
}
try {
const user = verifyToken(token);
socket.data.userId = user.id;
socket.data.email = user.email;
socket.data.name = user.name;
next();
} catch (error) {
next(new Error('Invalid token'));
}
});
io.on('connection', (socket) => {
console.log(`User connected: ${socket.data.userId}`);
// Track online users in Redis
redis.sadd('online_users', socket.data.userId);
// Join user's personal room for direct messages
socket.join(`user:${socket.data.userId}`);
// Handle room joining
socket.on('joinRoom', async (roomId) => {
// Verify user has access to room
const hasAccess = await checkRoomAccess(socket.data.userId, roomId);
if (!hasAccess) {
socket.emit('error', { code: 'FORBIDDEN', message: 'No access to room' });
return;
}
socket.join(`room:${roomId}`);
// Notify room members
socket.to(`room:${roomId}`).emit('userJoined', {
userId: socket.data.userId,
name: socket.data.name,
});
// Track room presence
await redis.sadd(`room:${roomId}:members`, socket.data.userId);
});
// Handle room leaving
socket.on('leaveRoom', async (roomId) => {
socket.leave(`room:${roomId}`);
socket.to(`room:${roomId}`).emit('userLeft', socket.data.userId);
await redis.srem(`room:${roomId}:members`, socket.data.userId);
});
// Handle messages
socket.on('sendMessage', async (data) => {
const { roomId, content } = data;
// Save message to database
const message = await saveMessage({
roomId,
userId: socket.data.userId,
content,
});
// Broadcast to room
io.to(`room:${roomId}`).emit('message', {
id: message.id,
content: message.content,
userId: socket.data.userId,
userName: socket.data.name,
roomId,
createdAt: message.createdAt.toISOString(),
});
});
// Handle typing indicators
socket.on('typing', ({ roomId, isTyping }) => {
socket.to(`room:${roomId}`).emit('typing', {
userId: socket.data.userId,
isTyping,
});
});
// Handle disconnection
socket.on('disconnect', async () => {
console.log(`User disconnected: ${socket.data.userId}`);
await redis.srem('online_users', socket.data.userId);
// Notify all rooms user was in
const rooms = Array.from(socket.rooms);
for (const room of rooms) {
if (room.startsWith('room:')) {
const roomId = room.replace('room:', '');
await redis.srem(`room:${roomId}:members`, socket.data.userId);
socket.to(room).emit('userLeft', socket.data.userId);
}
}
});
});
return io;
}
```
## Client-Side WebSocket Hook
```typescript
// hooks/useSocket.ts
import { useEffect, useRef, useCallback, useState } from 'react';
import { io, Socket } from 'socket.io-client';
interface UseSocketOptions {
url: string;
token: string;
onConnect?: () => void;
onDisconnect?: () => void;
onError?: (error: Error) => void;
}
export function useSocket({ url, token, onConnect, onDisconnect, onError }: UseSocketOptions) {
const socketRef = useRef<Socket | null>(null);
const [isConnected, setIsConnected] = useState(false);
const [reconnectAttempts, setReconnectAttempts] = useState(0);
useEffect(() => {
const socket = io(url, {
auth: { token },
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
});
socket.on('connect', () => {
setIsConnected(true);
setReconnectAttempts(0);
onConnect?.();
});
socket.on('disconnect', () => {
setIsConnected(false);
onDisconnect?.();
});
socket.on('connect_error', (error) => {
setReconnectAttempts((prev) => prev + 1);
onError?.(error);
});
socketRef.current = socket;
return () => {
socket.disconnect();
};
}, [url, token, onConnect, onDisconnect, onError]);
const emit = useCallback(<T>(event: string, data: T) => {
socketRef.current?.emit(event, data);
}, []);
const on = useCallback(<T>(event: string, callback: (data: T) => void) => {
socketRef.current?.on(event, callback);
return () => {
socketRef.current?.off(event, callback);
};
}, []);
const joinRoom = useCallback((roomId: string) => {
socketRef.current?.emit('joinRoom', roomId);
}, []);
const leaveRoom = useCallback((roomId: string) => {
socketRef.current?.emit('leaveRoom', roomId);
}, []);
return {
socket: socketRef.current,
isConnected,
reconnectAttempts,
emit,
on,
joinRoom,
leaveRoom,
};
}
```
## Chat Room Component
```typescript
// components/ChatRoom.tsx
'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useSocket } from '@/hooks/useSocket';
import { useAuth } from '@/hooks/useAuth';
interface Message {
id: string;
content: string;
userId: string;
userName: string;
createdAt: string;
}
interface ChatRoomProps {
roomId: string;
}
export function ChatRoom({ roomId }: ChatRoomProps) {
const { user, token } = useAuth();
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [typingUsers, setTypingUsers] = useState<Map<string, string>>(new Map());
const messagesEndRef = useRef<HTMLDivElement>(null);
const typingTimeoutRef = useRef<NodeJS.Timeout>();
const { socket, isConnected, joinRoom, leaveRoom, emit, on } = useSocket({
url: process.env.NEXT_PUBLIC_WS_URL!,
token,
onConnect: () => console.log('Connected to chat'),
onDisconnect: () => console.log('Disconnected from chat'),
});
// Join room on mount
useEffect(() => {
if (isConnected) {
joinRoom(roomId);
}
return () => {
if (isConnected) {
leaveRoom(roomId);
}
};
}, [isConnected, roomId, joinRoom, leaveRoom]);
// Listen for messages
useEffect(() => {
const unsubscribe = on<Message>('message', (message) => {
setMessages((prev) => [...prev, message]);
});
return unsubscribe;
}, [on]);
// Listen for typing indicators
useEffect(() => {
const unsubscribe = on<{ userId: string; isTyping: boolean }>('typing', (data) => {
setTypingUsers((prev) => {
const next = new Map(prev);
if (data.isTyping) {
next.set(data.userId, data.userId);
} else {
next.delete(data.userId);
}
return next;
});
});
return unsubscribe;
}, [on]);
// Auto-scroll to bottom
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
const sendMessage = useCallback(() => {
if (!input.trim()) return;
emit('sendMessage', { roomId, content: input });
setInput('');
// Stop typing indicator
emit('typing', { roomId, isTyping: false });
}, [input, roomId, emit]);
const handleInputChange = useCallback((value: string) => {
setInput(value);
// Send typing indicator
emit('typing', { roomId, isTyping: true });
// Clear previous timeout
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}
// Stop typing after 2 seconds of inactivity
typingTimeoutRef.current = setTimeout(() => {
emit('typing', { roomId, isTyping: false });
}, 2000);
}, [roomId, emit]);
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{messages.map((message) => (
<div
key={message.id}
className={`flex ${message.userId === user?.id ? 'justify-end' : 'justify-start'}`}
>
<div
className={`max-w-xs px-4 py-2 rounded-lg ${
message.userId === user?.id
? 'bg-blue-500 text-white'
: 'bg-gray-200 text-gray-900'
}`}
>
<p className="text-xs font-semibold">{message.userName}</p>
<p>{message.content}</p>
</div>
</div>
))}
<div ref={messagesEndRef} />
</div>
{typingUsers.size > 0 && (
<div className="px-4 py-2 text-sm text-gray-500">
{Array.from(typingUsers.values()).join(', ')} typing...
</div>
)}
<div className="p-4 border-t">
<div className="flex gap-2">
<input
type="text"
value={input}
onChange={(e) => handleInputChange(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
placeholder="Type a message..."
className="flex-1 px-4 py-2 border rounded-lg"
/>
<button
onClick={sendMessage}
disabled={!isConnected}
className="px-6 py-2 bg-blue-500 text-white rounded-lg disabled:opacity-50"
>
Send
</button>
</div>
</div>
</div>
);
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these WebSocket patterns: Implement authentication in middleware. Use rooms for efficient broadcasting. Handle reconnection gracefully. Add typing indicators for UX. Use Redis for scaling across servers.This WebSocket prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their websocket implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For WebSocket projects, consider mentioning your framework version, coding style, and any specific libraries you're using.