PHP WebSocket Server

Here is a simple event-driven WebSocket Server implementation in PHP 5.3.

  • Supports draft 75 and draft 76 (for newer Chrome browsers) of the WebSockets specification
  • Supports Flash Socket Policy requests (to allow current Firefox, Internet Explorer and other Flash-enabled browsers to talk to WebSockets with a special Flash wrapper)
  • Server behavior can be customized by Application modules

Get it from the GitHub repository.

It is inspired Moriz Wutz’ phpwebsockets, which is based on code by georgenava, but does not implement draft 76 and the Flash Policy.

Server example

<?php

class EchoApplication extends \WebSocket\Application\Application
{
    /** List of connected clients */
    private $clients = array();

    public function onConnect($client)
    {
        $this->clients[] = $client;
    }

    public function onDisconnect($client)
    {
        $key = array_search($client, $this->clients);
        if ($key) {
            unset($this->clients[$key]);
        }
    }

    public function onData($data, $client)
    {
        foreach ($this->clients as $sendto) {
            $sendto->send($data); // broadcast to all clients
        }
    }
}

$server = new \WebSocket\Server('localhost', 8000);
$server->registerApplication('echo', 
    EchoApplication::getInstance());
$server->run();

Client example

It comes with a small JavaScript client that makes WebSocket connection and message handling easy:

...
var server = new WebPush('ws://localhost:8000/echo');

server.bind('open', function() {
    // Connection openend...
    server.send("Hello, I'm there!");
});

server.bind('close', function() {
    // Connection closed... 
});

server.bind('message', function(data) {
    // Data received
});
...