Ratchet is a PHP library that provides you will the tools to create real time, bi-directional applications between clients and servers over WebSockets.

So, what are WebSockets? Simply put, it is a specification that defines an API establishing socket connections between a web browser and a server. This creates a persistent connection between both parties allowing them to send and receive data at any time. (#1)

Ratchet takes advantage of Composer which is an application written in PHP which manages all external PHP libraries within your project ensuring you're running the latest version and importing all the dependencies. Once you've installed Composer, lets start creating our first application. For full installation details please visit here: Installing Ratchet.

We firstly need to setup the Composer file to store our namespace:

    "autoload": {
        "psr-0": {
            "MyApp": "src"
    "require": {
        "cboden/Ratchet": "0.2.*"

Chat - Application

Once we've set that up, we'll create our chat class under the same namespace. This class will be our chat application consisting of 4 events:

  • onOpen - Called when a new client has connected
  • onMessage - Called when a message is received by a connection
  • onClose - Called when a connection is closed
  • onError - Called when an error occurs on a connection

Using these events, we need to implement the MessageComponentInterface:

namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
    protected $clients;
    public function __construct() {
        $this->clients = new \SplObjectStorage;
    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        echo "New connection! ({$conn->resourceId})\n";
    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        echo "Connection {$conn->resourceId} has disconnected\n";
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

Chat - Server Implementation

With that implemented and handling our events, we need to create the shell script; this is the file we will call from the command line to launch our application acting as the server:

use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__).'/vendor/autoload.php';
$server = IoServer::factory(
    new WsServer(
        new Chat()
    ), 8080

To start up the server application, we run the following command (terminal or SSH):

$ php bin/chat-server.php

Chat - From a Web Browser

Now we want to take advantage of the HTML5 WebSocket API through some simply Javascript:

var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
    console.log("Connection established!");
conn.onmessage = function(e) {

Once you open the web browser, you'll see a console message of "Connection established!" and you can now start sending messages to the other connected browsers:

conn.send('Hello World!');

It's as simple as that. With a simple jQuery logic on top, you can create a chat input and send those messages across to every connected member. You're able to update the application PHP logic to store chats in the database, handle a connected user etc. Featured in the resources section is a jQuery plugin that provides a graceful solution to support all older browsers using a traditional long-polling method.


To download all the source code demonstrated above, simple go to the Ratchet GitHub repository.

Have you used Ratchet before or any other PHP WebSocket APIs? Let me know your comments by mentioning #ALJTMedia on Twitter or leave a comment on our Facebook or Google+ page.

Other Resources

Ignite your brand, utilise user-generated content no matter where you or your audience are ›