Skip to main content
coding advanced

Implement WebSocket Connections

Get production-ready WebSocket code with error handling, authentication, and real-time features. Perfect for chat apps and live updates.

Works with: chatgptclaudegemini

Prompt Template

I need you to implement a complete WebSocket connection system for [APPLICATION_TYPE]. Please provide both client-side and server-side code with the following requirements: **Server Requirements:** - Use [SERVER_TECHNOLOGY] for the backend - Handle [MAX_CONNECTIONS] concurrent connections - Implement authentication using [AUTH_METHOD] - Include proper error handling and connection management - Support these message types: [MESSAGE_TYPES] - Add connection rate limiting and basic security measures **Client Requirements:** - [CLIENT_TECHNOLOGY] implementation - Automatic reconnection with exponential backoff - Message queuing for offline scenarios - Proper event handling for connection states - User-friendly error messages **Features to implement:** - [SPECIFIC_FEATURES] - Message broadcasting capabilities - Room/channel management if applicable - Heartbeat/ping-pong for connection health - Graceful shutdown handling **Additional considerations:** - Include comprehensive error handling - Add logging for debugging - Provide code comments explaining key concepts - Include basic testing examples - Consider scalability for production use Please structure the response with clear sections for server code, client code, usage examples, and deployment notes. Include any necessary package installations and configuration steps.

Variables to Customize

[APPLICATION_TYPE]

The type of application you're building

Example: real-time chat application

[SERVER_TECHNOLOGY]

Backend technology stack

Example: Node.js with Express and Socket.IO

[MAX_CONNECTIONS]

Expected concurrent connection limit

Example: 1000

[AUTH_METHOD]

Authentication mechanism

Example: JWT tokens

[MESSAGE_TYPES]

Types of messages the system should handle

Example: text messages, file uploads, typing indicators, user presence

[CLIENT_TECHNOLOGY]

Frontend technology for the client

Example: JavaScript/React

[SPECIFIC_FEATURES]

Custom features specific to your application

Example: private messaging, group chats, message history, user status updates

Example Output

# WebSocket Real-time Chat Implementation ## Server Code (Node.js + Socket.IO) ```javascript const express = require('express'); const http = require('http'); const socketIo = require('socket.io'); const jwt = require('jsonwebtoken'); const rateLimit = require('express-rate-limit'); const app = express(); const server = http.createServer(app); const io = socketIo(server, { cors: { origin: '*' }, maxHttpBufferSize: 1e6 }); // Rate limiting const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs }); // Authentication middleware io.use((socket, next) => { const token = socket.handshake.auth.token; try { const decoded = jwt.verify(token, process.env.JWT_SECRET); socket.userId = decoded.userId; next(); } catch (err) { next(new Error('Authentication error')); } }); const activeConnections = new Map(); io.on('connection', (socket) => { console.log(`User ${socket.userId} connected`); activeConnections.set(socket.userId, socket.id); // Handle different message types socket.on('text_message', (data) => { const message = { id: Date.now(), userId: socket.userId, content: data.content, timestamp: new Date(), type: 'text' }; // Broadcast to all clients in room socket.to(data.roomId).emit('new_message', message); }); socket.on('join_room', (roomId) => { socket.join(roomId); socket.emit('room_joined', { roomId, status: 'success' }); }); socket.on('disconnect', () => { console.log(`User ${socket.userId} disconnected`); activeConnections.delete(socket.userId); }); // Heartbeat socket.on('ping', () => { socket.emit('pong'); }); }); server.listen(3000, () => { console.log('WebSocket server running on port 3000'); }); ``` ## Client Code (JavaScript/React) ```javascript import { io } from 'socket.io-client'; class WebSocketClient { constructor(token) { this.token = token; this.socket = null; this.reconnectAttempts = 0; this.maxReconnectAttempts = 5; this.messageQueue = []; } connect() { this.socket = io('ws://localhost:3000', { auth: { token: this.token }, autoConnect: false }); this.socket.on('connect', () => { console.log('Connected to server'); this.reconnectAttempts = 0; this.flushMessageQueue(); }); this.socket.on('disconnect', () => { console.log('Disconnected from server'); this.handleReconnect(); }); this.socket.on('connect_error', (error) => { console.error('Connection error:', error.message); }); this.socket.connect(); } handleReconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { const delay = Math.pow(2, this.reconnectAttempts) * 1000; setTimeout(() => { this.reconnectAttempts++; this.socket.connect(); }, delay); } } sendMessage(roomId, content) { const message = { roomId, content, timestamp: Date.now() }; if (this.socket.connected) { this.socket.emit('text_message', message); } else { this.messageQueue.push(message); } } flushMessageQueue() { while (this.messageQueue.length > 0) { const message = this.messageQueue.shift(); this.socket.emit('text_message', message); } } } // Usage const client = new WebSocketClient('your-jwt-token'); client.connect(); ```

Pro Tips for Best Results

  • Always implement proper error handling and reconnection logic to handle network interruptions gracefully
  • Use authentication middleware to secure your WebSocket connections and prevent unauthorized access
  • Implement rate limiting and message validation to protect against spam and malicious attacks
  • Add heartbeat/ping-pong mechanisms to detect dead connections and clean up server resources
  • Consider using Redis for scaling WebSocket connections across multiple server instances in production

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like