Example #1
0
        $this->application = $application;
    }
    public function onRequest(Request $request, Socket $socket)
    {
        $path = $request->getUri()->getPath();
        if ($path == "/") {
            return yield from $this->onHttp($request, $socket);
        }
        if ($path == "/socket") {
            return yield from $this->onSocket($request, $socket);
        }
        return yield from $this->onError(404, $socket);
    }
    public function onError($code, Socket $socket) : Generator
    {
        (yield new BasicResponse($code));
    }
    public function onHttp(Request $request, Socket $socket) : Generator
    {
        $stream = new MemorySink();
        yield from $stream->end("\n            <script>\n                var socket = new WebSocket('ws://127.0.0.1:8888/socket');\n\n                socket.addEventListener('open', function() {\n                    console.log(arguments);\n                });\n\n                socket.addEventListener('message', function() {\n                    console.log(arguments);\n                });\n\n                socket.addEventListener('error', function() {\n                    console.log(arguments);\n                });\n\n                socket.addEventListener('close', function() {\n                    console.log(arguments);\n                });\n            </script>\n        ");
        (yield new BasicResponse(200, ["Content-Type" => "text/html", "Content-Length" => $stream->getLength()], $stream));
    }
    public function onSocket(Request $request, Socket $socket) : Generator
    {
        (yield $this->application);
    }
}
$server = new Server(new MyRequestHandler(new MyApplication()));
$server->listen(8888, "127.0.0.1");
Loop\run();
<?php

/**
 * Launch a websocket server instance
 *
 * @package    Launcher
 * @author     Romain Laneuville <*****@*****.**>
 */
use classes\IniManager as Ini;
use classes\ThrowableManager;
use classes\websocket\ServerRequestHandler;
use Icicle\WebSocket\Server\Server;
use Icicle\Loop;
require_once 'autoloader.php';
try {
    $params = Ini::getSectionParams('Socket');
    $server = new Server(new ServerRequestHandler());
    $server->listen($params['port'], $params['address']);
    Loop\run();
} catch (\Throwable $t) {
    $throwableManager = new ThrowableManager();
    $throwableManager->log($t);
} finally {
    exit(0);
}