WebSocket & Real-Time Communication

Bidirectional real-time communication with Socket.IO and native WebSockets. Build chat applications, live notifications, collaborative editing, real-time dashboards, IoT data streaming, and multiplayer features with scalable WebSocket infrastructure.

GET STARTEDTALK TO AN EXPERT

REAL-TIME WEBSOCKET INFRASTRUCTURE

Modern applications demand instant updates—whether it's chat messages, live notifications, collaborative document editing, or real-time analytics dashboards. WebSockets provide full-duplex communication channels over a single TCP connection, enabling truly real-time experiences. Our WebSocket development services include Socket.IO implementation with automatic reconnection, room-based messaging, presence detection, Redis adapter for horizontal scaling, message acknowledgments, and binary data support. Perfect for applications requiring instant data synchronization between client and server without the overhead of HTTP polling.

WHO IT'S FOR

Essential for chat applications, collaboration tools (Google Docs-style), live trading platforms, real-time gaming, IoT dashboards, live sports scores, auction platforms, and any application requiring instant data updates.

KEY BENEFITS

  • /True bidirectional communication
  • /Sub-second latency for instant updates
  • /Automatic reconnection on disconnect
  • /Room-based message broadcasting
  • /Presence detection (online/offline status)
  • /Redis adapter for multi-server scaling
  • /Binary data support for files/media
  • /Message acknowledgment and delivery confirmation
  • /Namespace isolation for different features
  • /Fallback to HTTP long-polling
WebSocket & Real-Time Communication

WHAT'S INCLUDED

01

Socket.IO Server Setup

Socket.IO server with Express integration, CORS configuration, namespace management, middleware for authentication, custom event handlers, and connection lifecycle management.

02

Bidirectional Communication

Client-to-server and server-to-client messaging, event-driven architecture, custom event names, payload validation, and TypeScript type safety for events.

03

Real-Time Chat System

One-on-one chat, group chat rooms, message history, typing indicators, read receipts, file attachments, emoji reactions, and message search functionality.

04

Live Notifications

Push notifications via WebSocket, notification badges, sound alerts, desktop notifications API, notification history, mark as read/unread, and notification preferences.

05

Collaborative Editing

Operational Transformation (OT) or CRDT algorithms, cursor positions, user presence indicators, conflict-free concurrent editing, and document versioning.

06

Room-Based Messaging

Dynamic room creation, join/leave room events, room-specific broadcasts, private rooms with access control, room member lists, and room metadata management.

07

Presence Detection

Online/offline status tracking, last seen timestamps, typing indicators, user activity status (active, idle, away), and connection state management.

08

Redis Adapter Scaling

Horizontal scaling with Redis PubSub, sticky sessions with load balancer, multi-server message broadcasting, connection state synchronization across servers.

09

IoT Data Streaming

Real-time sensor data streaming, device telemetry, time-series data visualization, high-frequency updates (10-100 msgs/sec), and data buffering for performance.

10

Authentication & Security

JWT token validation on connection, socket-level middleware, rate limiting per socket, IP blacklisting, message encryption, and XSS protection.

11

Message Acknowledgment

Delivery confirmation with callbacks, retry logic for failed messages, message queue for offline users, persistent storage with MongoDB, and deduplication.

12

Performance Optimization

Message batching for high throughput, binary data compression, connection pooling, heartbeat intervals, idle timeout configuration, and memory leak prevention.

HOW WE DO IT

1

Architecture Planning

Define real-time features, design event schema, plan room structure, choose authentication strategy, estimate concurrent connection load, and select scaling approach.

2

Socket.IO Server Setup

Initialize Socket.IO with Express, configure CORS and authentication middleware, set up namespaces for feature isolation, and implement connection handlers.

3

Event Implementation

Create custom event listeners, implement room join/leave logic, build message broadcasting, add presence tracking, and handle disconnection scenarios.

4

Client Integration

Set up Socket.IO client (JavaScript/React/React Native), implement automatic reconnection, handle event listeners, create UI for real-time updates, and test connection stability.

5

Scaling with Redis

Configure Redis adapter for multi-server deployment, set up load balancer with sticky sessions, test cross-server message delivery, and implement connection migration.

6

Testing & Monitoring

Load testing with Artillery or k6, test reconnection scenarios, monitor active connections, track message delivery rates, and set up alerts for connection spikes.

TOOLS & TECHNOLOGIES

Socket.IO
WebSocket
Node.js
Express
Redis
Redis Adapter
JWT
MongoDB
React
Vue.js
TypeScript
PM2
Nginx
Docker
Kubernetes
AWS ELB
Artillery
Grafana
Prometheus
Sentry
DataDog
WebRTC
Server-Sent Events

RELATED SERVICES

READY TO GET STARTED?

Let's discuss your project and see how we can help bring your vision to life.

START A PROJECT

WEBSOCKET EXAMPLES

SOCKET.IO SERVER

// Socket.IO Server with Redis Adapter
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('redis');
const jwt = require('jsonwebtoken');

const app = express();
const server = http.createServer(app);

// Socket.IO with CORS
const io = socketIO(server, {
  cors: {
    origin: process.env.FRONTEND_URL,
    credentials: true
  }
});

// Redis adapter for scaling
const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();

Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
  io.adapter(createAdapter(pubClient, subClient));
  console.log('Redis adapter connected');
});

// Authentication middleware
io.use((socket, next) => {
  const token = socket.handshake.auth.token;

  if (!token) {
    return next(new Error('Authentication error'));
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    socket.userId = decoded.id;
    socket.username = decoded.username;
    next();
  } catch (err) {
    next(new Error('Invalid token'));
  }
});

// Connection handler
io.on('connection', (socket) => {
  console.log(`User connected: ${socket.userId}`);

  // Join user-specific room
  socket.join(`user:${socket.userId}`);

  // Store user socket mapping
  socket.broadcast.emit('user:online', {
    userId: socket.userId,
    username: socket.username
  });

  // Join chat room
  socket.on('room:join', async (roomId) => {
    socket.join(`room:${roomId}`);

    // Get room members
    const sockets = await io.in(`room:${roomId}`).fetchSockets();
    const members = sockets.map(s => ({
      userId: s.userId,
      username: s.username
    }));

    socket.emit('room:members', members);

    io.to(`room:${roomId}`).emit('room:user_joined', {
      userId: socket.userId,
      username: socket.username
    });
  });

  // Chat message
  socket.on('message:send', async (data) => {
    const { roomId, content } = data;

    // Save to database
    const message = await Message.create({
      roomId,
      userId: socket.userId,
      content,
      createdAt: new Date()
    });

    // Broadcast to room
    io.to(`room:${roomId}`).emit('message:new', {
      id: message.id,
      userId: socket.userId,
      username: socket.username,
      content: message.content,
      createdAt: message.createdAt
    });

    // Send acknowledgment
    socket.emit('message:sent', { messageId: message.id });
  });

  // Typing indicator
  socket.on('typing:start', ({ roomId }) => {
    socket.to(`room:${roomId}`).emit('typing:user', {
      userId: socket.userId,
      username: socket.username
    });
  });

  // Disconnection
  socket.on('disconnect', () => {
    console.log(`User disconnected: ${socket.userId}`);

    socket.broadcast.emit('user:offline', {
      userId: socket.userId
    });
  });
});

server.listen(3000, () => {
  console.log('Socket.IO server running on port 3000');
});

SOCKET.IO REACT CLIENT

// Socket.IO React Client Hook
import { useEffect, useState, useRef } from 'react';
import { io } from 'socket.io-client';

export function useSocket(token) {
  const [socket, setSocket] = useState(null);
  const [connected, setConnected] = useState(false);
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    if (!token) return;

    // Initialize socket
    const newSocket = io(process.env.REACT_APP_SOCKET_URL, {
      auth: { token },
      transports: ['websocket'],
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5
    });

    // Connection events
    newSocket.on('connect', () => {
      console.log('Socket connected');
      setConnected(true);
    });

    newSocket.on('disconnect', () => {
      console.log('Socket disconnected');
      setConnected(false);
    });

    newSocket.on('connect_error', (error) => {
      console.error('Connection error:', error);
    });

    // Message events
    newSocket.on('message:new', (message) => {
      setMessages(prev => [...prev, message]);
    });

    setSocket(newSocket);

    return () => {
      newSocket.close();
    };
  }, [token]);

  // Send message
  const sendMessage = (roomId, content) => {
    if (!socket) return;

    socket.emit('message:send', { roomId, content }, (ack) => {
      console.log('Message acknowledged:', ack);
    });
  };

  // Join room
  const joinRoom = (roomId) => {
    if (!socket) return;
    socket.emit('room:join', roomId);
  };

  // Typing indicator
  const startTyping = (roomId) => {
    if (!socket) return;
    socket.emit('typing:start', { roomId });
  };

  return {
    socket,
    connected,
    messages,
    sendMessage,
    joinRoom,
    startTyping
  };
}

// Usage in component
function ChatRoom({ roomId, token }) {
  const {
    connected,
    messages,
    sendMessage,
    joinRoom,
    startTyping
  } = useSocket(token);

  const [input, setInput] = useState('');

  useEffect(() => {
    if (connected) {
      joinRoom(roomId);
    }
  }, [connected, roomId]);

  const handleSend = () => {
    if (input.trim()) {
      sendMessage(roomId, input);
      setInput('');
    }
  };

  const handleTyping = () => {
    startTyping(roomId);
  };

  return (
    <div>
      <div className="status">
        {connected ? '🟢 Connected' : '🔴 Disconnected'}
      </div>

      <div className="messages">
        {messages.map(msg => (
          <div key={msg.id}>
            <strong>{msg.username}:</strong> {msg.content}
          </div>
        ))}
      </div>

      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        onKeyPress={handleTyping}
        placeholder="Type a message..."
      />
      <button onClick={handleSend}>Send</button>
    </div>
  );
}

PRESENCE DETECTION SYSTEM

// Presence detection with Redis
const redis = require('redis');
const redisClient = redis.createClient({ url: process.env.REDIS_URL });
redisClient.connect();

// Presence manager
class PresenceManager {
  constructor(io, redis) {
    this.io = io;
    this.redis = redis;
  }

  async setUserOnline(userId, socketId) {
    const key = `presence:${userId}`;

    await this.redis.hSet(key, {
      status: 'online',
      socketId: socketId,
      lastSeen: Date.now().toString()
    });

    await this.redis.expire(key, 3600); // 1 hour TTL

    // Broadcast to friends
    const friends = await this.getUserFriends(userId);
    friends.forEach(friendId => {
      this.io.to(`user:${friendId}`).emit('presence:update', {
        userId,
        status: 'online'
      });
    });
  }

  async setUserOffline(userId) {
    const key = `presence:${userId}`;

    await this.redis.hSet(key, {
      status: 'offline',
      lastSeen: Date.now().toString()
    });

    // Broadcast to friends
    const friends = await this.getUserFriends(userId);
    friends.forEach(friendId => {
      this.io.to(`user:${friendId}`).emit('presence:update', {
        userId,
        status: 'offline',
        lastSeen: Date.now()
      });
    });
  }

  async getUserStatus(userId) {
    const key = `presence:${userId}`;
    const data = await this.redis.hGetAll(key);

    if (!data || !data.status) {
      return { status: 'offline' };
    }

    return {
      status: data.status,
      lastSeen: parseInt(data.lastSeen)
    };
  }

  async getUserFriends(userId) {
    // Get from database
    const friendships = await Friendship.findAll({
      where: { userId },
      attributes: ['friendId']
    });
    return friendships.map(f => f.friendId);
  }
}

const presenceManager = new PresenceManager(io, redisClient);

// Use in connection handler
io.on('connection', async (socket) => {
  await presenceManager.setUserOnline(socket.userId, socket.id);

  socket.on('disconnect', async () => {
    await presenceManager.setUserOffline(socket.userId);
  });

  // Get friends status
  socket.on('presence:get_friends', async () => {
    const friends = await presenceManager.getUserFriends(socket.userId);
    const statuses = await Promise.all(
      friends.map(async (friendId) => ({
        userId: friendId,
        ...(await presenceManager.getUserStatus(friendId))
      }))
    );

    socket.emit('presence:friends_status', statuses);
  });
});