What is Ratchet Library, and how it is work

Ratchet is a PHP library used to build real-time, bi-directional WebSocket applications. It’s built on top of ReactPHP, which allows PHP to run asynchronously, meaning it can handle multiple connections at the same time — a key requirement for WebSocket servers.

What is Ratchet?

  • A WebSocket server library for PHP
  • Built on ReactPHP event loop
  • Runs as a long-running CLI process
  • Allows persistent connections between clients and the server (unlike regular HTTP)

How Ratchet Works (Conceptually)

  1. Client (usually browser) connects via WebSocket (e.g. ws://yourserver:8080).
  2. Ratchet server accepts the connection and performs the WebSocket handshake.
  3. Ratchet emits events like:
    • onOpen – When a client connects
    • onMessage – When a client sends a message
    • onClose – When a client disconnects
    • onError – When an error occurs
  4. You can send messages to clients, broadcast to all, or do custom logic.

Basic Example: Chat Server Using Ratchet

Step 1: Install via Composer

composer require cboden/ratchet

Step 2: Create a Chat Server

<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

require __DIR__ . '/vendor/autoload.php';

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                $client->send("User {$from->resourceId} says: $msg");
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}

Step 3: Run the Server

use Ratchet\Server\IoServer;

$server = IoServer::factory(
    new Chat(),
    8080
);

$server->run();
php your-chat-server.php

Why Use Ratchet?

  • Real-time messaging (chat, notifications, live stats)
  • Push updates from server without polling
  • Low latency, always-open connection
  • Native PHP solution (no Node.js or external services required)

Typical Use Cases

  • Chat applications
  • Real-time dashboards
  • Live notifications (e.g. orders, messages)
  • Online games or collaborative tools

Leave a Reply

Your email address will not be published. Required fields are marked *