#}

API Real-Time Features

Build live applications with WebSockets, channels, and real-time data streaming

Real-Time Features

Overview

GEMVC provides comprehensive real-time communication capabilities through WebSocket technology powered by OpenSwoole.

WebSockets Bidirectional communication
Channels Organized message routing
Broadcasting Send to all clients
Redis Pub/Sub Scale across servers
info: Real-time features require OpenSwoole. They are not available with Apache/PHP-FPM.

WebSocket Handler

GEMVC provides the SwooleWebSocketHandler class for managing WebSocket connections:

WebSocket Handler
use Gemvc\Swoole\SwooleWebSocketHandler;

class ChatHandler extends SwooleWebSocketHandler
{
    public function onMessage(\$server, \$frame): void
    {
        \$data = json_decode(\$frame->data, true);
        
        // Broadcast to all clients in channel
        \$this->broadcastToChannel('chat', [
            'user' => \$data['user'],
            'message' => \$data['message']
        ]);
    }
    
    public function onOpen(\$server, \$request): void
    {
        // Client connected
        \$this->subscribeToChannel(\$request->fd, 'chat');
    }
    
    public function onClose(\$server, \$fd): void
    {
        // Client disconnected
        \$this->unsubscribeFromChannel(\$fd, 'chat');
    }
}

Key Features

  • Connection Management - Track and manage active WebSocket connections
  • Channel Subscriptions - Organize clients into logical groups
  • Broadcasting - Send messages to all clients or specific channels
  • JWT Authentication - Secure WebSocket connections with tokens
  • Rate Limiting - Protect against message flooding

Client-Side Example

JavaScript Client
// JavaScript WebSocket client
const ws = new WebSocket('wss://api.example.com/ws');

ws.onopen = () => {
    console.log('Connected!');
    ws.send(JSON.stringify({
        action: 'subscribe',
        channel: 'notifications'
    }));
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
};

ws.onclose = () => {
    console.log('Disconnected');
};

Scaling with Redis

For multi-server deployments, use Redis Pub/Sub to broadcast messages across all instances:

Redis Configuration
# .env
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PREFIX=gemvc:
Tip: Redis Pub/Sub enables WebSocket messages to reach clients connected to any server instance in your cluster.

Use Cases

Chat Applications

Real-time messaging with channels and private rooms

Live Notifications

Push notifications to users instantly

Live Dashboards

Real-time data visualization and updates

Multiplayer Games

Real-time game state synchronization

Next Steps