PHP code example of timostamm / websocket-server

1. Go to this page and download the library: Download timostamm/websocket-server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

timostamm / websocket-server example snippets


$loop = Factory::create(); // use a react event loop

// start server
$server = new WebsocketServer($loop, [
    'uri' => '127.0.0.1:23080'
]);

// add a controller 
$server->route([
    'match' => '/example/*',
    'controller' => new class() implements ControllerInterface
    {
        function onOpen(WebSocket $connection): void
        {
            print $connection . ' connected. Sending a "Hello".' . PHP_EOL;
            $connection->send('Hello');
        }

        function onMessage(WebSocket $from, string $payload, bool $binary): void
        {
            print $from . ' sent: ' . $payload . PHP_EOL;
        }

        function onClose(WebSocket $connection, ?Throwable $error): void
        {
            print $connection . ' disconnected.' . PHP_EOL;
        }

    }
]);

// This error handler will be called when an exception was thrown
// by a filter, a controller method or the underlying tcp server.
$server->on('error', function (Throwable $error) {
    print 'Server error: ' . $error->getMessage() . PHP_EOL;
});

$loop->run(); // the react event loop processes socket connections

$server->route([
    'match' => '/example/*',
    'controller' => $controller
]);

$server->route([
    'controller' => $controller
]);

$server->route([
    'protocols' => ['soap'],
    'controller' => $controller
]);

$server->filter('example/403', function () {
    throw ResponseException::create(403);
});

$server->filter('example/add-attribute', function (ServerRequestInterface $request) {
    return $request->withAttribute('X-filter', 'passed');
});

$server->filter('example/origin', new OriginFilter(['example.com']));

$server->route([
    'match' => '/example/*', 
    'filter' => function(ServerRequestInterface $request){
        if ($request->getRequestTarget() === '/example/forbidden') {
            throw ResponseException::create(403);
        }
    }
    'controller' => ...
]);

class MyCtrl implements ControllerInterface, LoopAwareInterface ConnectionListAwareInterface, OnShutDownInterface, OnLastCloseInterface, OnFirstOpenInterface
{

    function setLoop(\React\EventLoop\LoopInterface $loop, callable $exceptionHandler): void
    {
        print 'Got loop.' . PHP_EOL;
    }

    function setConnections(\SplObjectStorage $webSockets): void
    {
        print 'Got connection list.' . PHP_EOL;
    }
    
    function onShutDown(): PromiseInterface
    {
         // Will be called when the server is asked to shutdown.
         // Use this hook to finish important tasks, then resolve the promise.
    }

    function onLastClose(WebSocket $socket): void
    {
        print 'Last connection closed.' . PHP_EOL;
    }

    function onFirstOpen(WebSocket $socket): void
    {
        print 'First connection opened.' . PHP_EOL;
    }

    function onOpen(WebSocket $socket): void
    {
        print $socket . ' connected. Sending a "Hello".' . PHP_EOL;
        $socket->send('Hello');
    }

    function onMessage(WebSocket $from, string $payload, bool $binary): void
    {
        print $from . ' received: ' . $payload . PHP_EOL;
    }

    function onClose(WebSocket $socket): void
    {
        print $socket . ' disconnected.' . PHP_EOL;
    }

    function onError(WebSocket $socket, \Throwable $error): void
    {
        print $socket . ' error: ' . $error->getMessage() . PHP_EOL;
    }

}