in Programming

Wrench – The new HTML5 Websocket Class Hero for PHP

Wrench is an up-to-date websocket server implementation in php that works with current chrome and firefox versions. The library has no external dependencies, just php 5.3 is required. Some code says more than thousand words …

A simple server looks like …

 
#!/usr/bin/env php
<?php
 
require(__DIR__ . '/lib/SplClassLoader.php');
 
$classLoader = new SplClassLoader('Wrench', __DIR__ . '/lib');
$classLoader->register();
 
$server = new \Wrench\Server('ws://0.0.0.0:8080/', array(
    'allowed_origins' => array('bohuco.net'),
));
 
$server->registerApplication('echo', new \Wrench\Application\EchoApplication());
$server->run();

It’s important to bind the Socket on IP 0.0.0.0 … i first tried it with 127.0.0.1 then the socket is not reachable from external network. If you have a firewall like on Amazon EC2 you must configure it so, that the port (eg.: 8080) is open.

The actual application …

… is separated into another class/namespace … here is an example of a simple EchoApplication that echos the received message back:

 
namespace Wrench\Application;
 
use Wrench\Application\Application;
use Wrench\Application\NamedApplication;
 
class EchoApplication extends Application {
    public function onData($data, $client) {
 
        $client->send($data);
 
    }
}

The javascript part would look like this …

The last part (/echo) of the websocket address is the application name, this name must be registered in server.php with the registerApplication-method (see above).

 
if ("WebSocket" in window) {
    ws = new WebSocket("ws://46.51.177.248:8080/echo");
 
    ws.onopen = function() {
        ws.send('INIT');
    };
 
    ws.onmessage = function(evt) {
        console.log(evt.data);
    };
 
    ws.onclose = function(evt) {
    	ws.send('MESSAGE');
    };
 
    ws.onerror = function(evt) { }
 
} else {
	alert("WebSocket NOT supported by your Browser!");
}

More infos and documentation about Wrench: