Ratchet

repository·0.4.x·Indexed 27 days ago

https://github.com/ratchetphp/ratchet

A PHP library for asynchronously serving WebSockets, enabling the creation of real-time applications. It provides the Ratchet\App facade for server setup and routing, the Ratchet\MessageComponentInterface for handling connection lifecycles, and support for the Web Application Messaging Protocol (WAMP) via Ratchet\Wamp\ServerProtocol. Compatible with PHP 5.4 through PHP 8+.

Tokens
2.8K
Snippets
5
Records
17
Agent score
91%

What's inside Ratchet

  1. Install Ratchet via Composer

    0.4.x

    The recommended way to install Ratchet is through Composer. This will install the latest supported version.

    Ratchet supports running on legacy PHP 5.4 through current PHP 8+. However, it is highly recommended to use the latest supported PHP version.

    composer require cboden/ratchet:^0.4.4
  2. Implement a WAMP Server using ServerProtocol

    0.4.x

    To build a WAMP (Web Application Messaging Protocol) server, you must instantiate Ratchet\Wamp\ServerProtocol by passing an implementation of WampServerInterface to its constructor. This implementation will act as the decorator that handles the actual business logic for WAMP events like calls, subscriptions, and publishing.

    When a client connects, ServerProtocol wraps the standard ConnectionInterface into a WampConnection object, which is then passed to your server component's onOpen method.

  3. Run a Ratchet WebSocket Server

    0.4.x

    To start a WebSocket server, instantiate Ratchet\App, define routes for your components, and call run().

    Example workflow:

    1. Create a class implementing MessageComponentInterface.
    2. Initialize new Ratchet\App('host', port).
    3. Use $app->route($path, $component, $selectors) to map URL paths to your logic.
    4. Execute the script via the CLI.
    <?php
    use Ratchet\MessageComponentInterface;
    use Ratchet\ConnectionInterface;
    
    require __DIR__ . '/vendor/autoload.php';
    
    class MyChat implements MessageComponentInterface {
        protected $clients;
        public function __construct() {
            $this->clients = new \SplObjectStorage;
        }
        public function onOpen(ConnectionInterface $conn) {
            $this->clients->attach($conn);
        }
        public function onMessage(ConnectionInterface $from, $msg) {
            foreach ($this->clients as $client) {
                if ($from != $client) {
                    $client->send($msg);
                }
            }
        }
        public function onClose(ConnectionInterface $conn) {
            $this->clients->detach($conn);
        }
        public function onError(ConnectionInterface $conn, \Exception $e) {
            $conn->close();
        }
    }
    
    $app = new Ratchet\App('localhost', 8080);
    $app->route('/chat', new MyChat, array('*'));
    $app->route('/echo', new Ratchet\Server\EchoServer, array('*'));
    $app->run();

    Run the server with:

    php chat.php
  4. Connect to a Ratchet Server from JavaScript

    0.4.x

    Once your Ratchet server is running, you can connect to it using the standard browser WebSocket API.

    var conn = new WebSocket('ws://localhost:8080/echo');
    conn.onmessage = function(e) { console.log(e.data); };
    conn.onopen = function(e) { conn.send('Hello Me!'); };
  5. Implement a WebSocket Message Component

    0.4.x

    To handle WebSocket logic, implement the Ratchet\MessageComponentInterface. This interface requires four methods to manage the lifecycle of a connection:

    • onOpen(ConnectionInterface $conn): Called when a new connection is established. Use this to track the connection (e.g., adding it to an SplObjectStorage).
    • onMessage(ConnectionInterface $from, $msg): Called when a message is received from a client. Use this to process data or broadcast to other clients.
    • onClose(ConnectionInterface $conn): Called when a connection is closed. Use this to clean up stored connections.
    • onError(ConnectionInterface $conn, \Exception $e): Called when an error occurs on a connection. Typically used to close the connection.
    <?php
    use Ratchet\MessageComponentInterface;
    use Ratchet\ConnectionInterface;
    
    class MyChat implements MessageComponentInterface {
        protected $clients;
    
        public function __construct() {
            $this->clients = new \SplObjectStorage;
        }
    
        public function onOpen(ConnectionInterface $conn) {
            $this->clients->attach($conn);
        }
    
        public function onMessage(ConnectionInterface $from, $msg) {
            foreach ($this->clients as $client) {
                if ($from != $client) {
                    $client->send($msg);
                }
            }
        }
    
        public function onClose(ConnectionInterface $conn) {
            $this->clients->detach($conn);
        }
    
        public function onError(ConnectionInterface $conn, \Exception $e) {
            $conn->close();
        }
    }
  6. Resolve URIs with getUri()

    0.4.x
    Use getUri() to resolve a URI that may contain a CURIE prefix. If the provided $uri contains a separator (:) and the prefix part matches a previously registered prefix via prefix(), it returns the full URI combined with the action (e.g., prefix#action). If no prefix is found or the URI is already a full URL, it returns the original $uri.
  7. Use OriginCheck to prevent unauthorized WebSocket connections

    0.4.x

    The OriginCheck class acts as a middleware to ensure that WebSocket connections originate from expected domains. This protects your application from being used by unauthorized websites via cross-site WebSocket hijacking.

    Security Note: This check can be spoofed by non-browser clients. It is intended to protect against browser-based attacks.

  8. Initialize a WebSocket server with the App class

    0.4.x

    The Ratchet\App class is an opinionated facade used to quickly set up a WebSocket server. It handles routing, origin checking, and Flash policy configuration by default.

    Constructor Parameters

    ParameterTypeDefaultDescription
    $httpHoststring'localhost'The HTTP hostname clients connect to. Must match the hostname used in the client-side JavaScript new WebSocket('ws://$httpHost') call.
    $portint8080The port to listen on. If set to 80, it assumes production and configures Flash accordingly.
    $addressstring'127.0.0.1'The IP address to bind to. Use '0.0.0.0' to listen on all available network interfaces.
    $loop?LoopInterfacenullAn optional React\EventLoop\LoopInterface instance. If null, a default loop is created.
    $contextarray[]Context options for the underlying socket server.
  9. Register routes and endpoints using App::route()

    0.4.x

    Use the route() method to map a URI path to a specific component (like a WebSocket message handler or a WAMP server).

    Parameters

    ParameterTypeDescription
    $pathstringThe URI path the client will connect to.
    $controllerComponentInterfaceYour application logic. Supports HttpServerInterface, WampServerInterface, MessageComponentInterface, or WsMessageComponentInterface.
    $allowedOriginsarrayAn array of hosts allowed to connect. Defaults to the $httpHost provided in the constructor. Use ['*'] to allow any origin.
    $httpHoststring|nullOptional override for the $httpHost used for origin checking.

    Behavior

    • If the controller is a WampServerInterface or MessageComponentInterface, it is automatically wrapped in a WsServer with keep-alive enabled.
    • If $allowedOrigins is not ['*'], an OriginCheck decorator is automatically applied to enforce security.
  10. Respond to WAMP client calls with callError()

    0.4.x

    Use callError() to send an error response to a client's RPC call.

    Parameters:

    • $id: The unique ID provided by the client.
    • $errorUri: A string or Topic object identifying the specific error.
    • $desc: A developer-oriented description of the error.
    • $details: (Optional) A human-readable detail message.