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
require(__DIR__ . '/lib/SplClassLoader.php');
$classLoader = new SplClassLoader('Wrench', __DIR__ . '/lib');
$server = new \Wrench\Server('ws://', array(
    'allowed_origins' => array(''),
$server->registerApplication('echo', new \Wrench\Application\EchoApplication());

It’s important to bind the Socket on IP … i first tried it with 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) {

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://");
    ws.onopen = function() {
    ws.onmessage = function(evt) {
    ws.onclose = function(evt) {
    ws.onerror = function(evt) { }
} else {
	alert("WebSocket NOT supported by your Browser!");

More infos and documentation about Wrench: