Skip to content
Vladimir Goncharov edited this page Mar 15, 2016 · 13 revisions
Installation

execute command: composer require morozovsk/websocket

Example

create file sample.php:

#!/usr/bin/env php
<?php

if (empty($argv[1]) || !in_array($argv[1], array('start', 'stop', 'restart'))) {
    die("need parameter (start|stop|restart)\r\n");
}

$config = array(
    'class' => 'morozovsk\websocket\examples\chat\server\ChatWebsocketDaemonHandler',
    'pid' => '/tmp/websocket_chat.pid',
    'websocket' => 'tcp://127.0.0.1:8000',
);

require_once __DIR__ . '/../../../../autoload.php';

$WebsocketServer = new morozovsk\websocket\Server($config);

call_user_func(array($WebsocketServer, $argv[1]));

create file ChatWebsocketDaemonHandler.php:

<?php
namespace morozovsk\websocket\examples\chat\server;

class ChatWebsocketDaemonHandler extends \morozovsk\websocket\Daemon
{
    protected function onOpen($connectionId, $info) {
        //call when new client connect to server
    }

    protected function onClose($connectionId) {
        //call when existing client close connection
    }

    protected function onMessage($connectionId, $data, $type) {
        //call when new message from existing client

        $message = "user #{$connectionId}: $data";

        //send message to all client
        foreach ($this->clients as $clientId => $client) {
            $this->sendToClient($clientId, $message);
        }
    }
}

execute command: php sample.php start

Configuration
$config = array(
    'class' => 'class that will handle connections',
    'pid' => 'pid-file',
    'websocket' => 'socket that will handle websocket-connections',
    //'eventDriver' => 'handler type'
        //socket_select (default, not need install, can handle maximum 2000 connections) - http://php.net/manual/en/function.socket-select.php
        //pecl/event (need install) - https://pecl.php.net/package/event
        //pecl/libevent (need install) - https://pecl.php.net/package/libevent
    //'localsocket' => 'socket for handle local-connections (without websocket-protocol)'
    //'master' => 'for connect to other local socket (without websocket-protocol)'
);
pecl/event (needed for more then 1000 connections without php recompilation)
needed packages: php-pear libevent-2.0-5 libevent-dev libssl-dev pkg-config
command: pecl install event
add "extension=event.so" to php.ini
performance test
command: php Test.php start {websocket} {connections >= 1} {workers >= 1}
examples for open 10000 connections:
php Test.php start tcp://127.0.0.1:8001 10000 1
php Test.php start tcp://127.0.0.1:8001 1000 10