WsServer (WebSocket server)

Purpose of this Component

This component allows your server to communicate with web browsers that use the W3C WebSocket API. Ratchet passes all WebSocket protocol tests from the Autobahn Testsuite.

Note: This component is automatically created for you when you add a route to an App instance.

Events triggered by this Component

As found in the API Docs: Triggered events are propagated through a MessageComponentInterface object passed to the __construct.

  • onOpen (ConnectionInterface $conn) - A new client connection has been opened
  • onClose (ConnectionInterface $conn) - A client connection is about to, or has closed
  • onMessage (ConnectionInterface $from, string $message) - A data message has been received
  • onError (ConnectionInterface $from, Exception $error) - An error has occurred with a Connection

Configuration methods

  • void enableKeepAlive (LoopInterface $loop, integer $interval) - Ping every connected client every $interval. If there is no response by the next cycle the client is disconnected.
  • void setStrictSubProtocolCheck (boolean $enable) - If enabled the server will reject client connections that don't meet at least one of the specified sub-protocols defined by the server (default true).

Functions callable on Connections

  • send (string $message) - Send a message (string) to the client
  • close (integer $code = 1000) - Gracefully close the connection to the client with a valid close code

Parameters added to each Connection

(Psr\Http\Message\RequestInterface $httpRequest) - A PSR-7 Request object containing all the information from the initial HTTP connection
(StdClass $WebSocket) - Contains a single boolean value $closing indicating if the connection has begun the shutdown protocol.

Wraps other components nicely

Wrapped by other components nicely


// Your shell script
use Ratchet\WebSocket\WsServer;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;

    $ws = new WsServer(new MyChat);

    // Make sure you're running this as root
    $server = IoServer::factory(new HttpServer($ws));