Ratchet WebSocket Library for PHP: Creating Real-Time on Your Website

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is WebSocket and why do you need the Ratchet library for PHP?

\n

WebSocket is a protocol that provides a persistent two-way connection between a client (browser) and a server. Unlike classic HTTP, where only the client initiates requests, WebSocket allows the server to send data instantly without waiting for a request. This is an ideal solution for chats, real-time notifications, online games, trackers, and any applications where low latency is important.

\n

Standard PHP does not have built-in WebSocket support, but the Ratchet library (using the ReactPHP component) fills this gap. Ratchet is an asynchronous library that allows you to run a WebSocket server directly from PHP, handling multiple connections simultaneously without blocking.

\n\n

Key Features of Ratchet

\n
    \n
  • Asynchronous — based on ReactPHP, does not block the thread while waiting for data.
  • \n
  • Protocol Support — WebSocket (RFC 6455), as well as HTTP components (for hybrid applications).
  • \n
  • Simplicity — minimal code to run a server.
  • \n
  • Scalability — can be combined with ZeroMQ or Redis for cluster operation.
  • \n
  • Compatibility — works with any modern browser via the built-in WebSocket object.
  • \n
\n\n

Installing Ratchet

\n

Installation is done via Composer. Open a terminal in the project root and run:

\n
composer require cboden/ratchet
\n

After installation, all dependencies including ReactPHP will appear in the vendor folder.

\n\n

Creating a Simple WebSocket Server with Ratchet

\n

Let's create a file server.php:

\n
<?php\nrequire 'vendor/autoload.php';\n\nuse Ratchet\\MessageComponentInterface;\nuse Ratchet\\ConnectionInterface;\nuse Ratchet\\Server\\IoServer;\nuse Ratchet\\Http\\HttpServer;\nuse Ratchet\\WebSocket\\WsServer;\n\nclass Chat implements MessageComponentInterface {\n    protected $clients;\n\n    public function __construct() {\n        $this->clients = new \\SplObjectStorage;\n    }\n\n    public function onOpen(ConnectionInterface $conn) {\n        $this->clients->attach($conn);\n        echo "New connection: {$conn->resourceId}\\n";\n    }\n\n    public function onMessage(ConnectionInterface $from, $msg) {\n        foreach ($this->clients as $client) {\n            if ($from !== $client) {\n                $client->send($msg);\n            }\n        }\n    }\n\n    public function onClose(ConnectionInterface $conn) {\n        $this->clients->detach($conn);\n        echo "Disconnection: {$conn->resourceId}\\n";\n    }\n\n    public function onError(ConnectionInterface $conn, \\Exception $e) {\n        echo "Error: {$e->getMessage()}\\n";\n        $conn->close();\n    }\n}\n\n$server = IoServer::factory(\n    new HttpServer(\n        new WsServer(\n            new Chat()\n        )\n    ),\n    8080\n);\n\necho "Server started on port 8080\\n";\n$server->run();
\n\n

Code Explanation

\n
    \n
  • Chat — a class implementing MessageComponentInterface. In onOpen we save the connection, in onMessage we broadcast the message to everyone except the sender.
  • \n
  • IoServer::factory — creates a server based on ReactPHP. We wrap our component in WsServer (for WebSocket) and HttpServer (for compatibility with HTTP requests).
  • \n
  • The server listens on port 8080. Start it with the command: php server.php.
  • \n
\n\n

Client Side (JavaScript)

\n

Create an HTML file client.html:

\n
<!DOCTYPE html>\n<html>\n<head>\n    <title>WebSocket Chat</title>\n    <script>\n        const ws = new WebSocket('ws://localhost:8080');\n\n                    

Recommendations