PHP code example of brash / websocket-middleware

1. Go to this page and download the library: Download brash/websocket-middleware 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/ */

    

brash / websocket-middleware example snippets


    

$connectionHandlerInterface = new class extends AbstractTextMessageHandler
{
    private array $connections;

    public function __construct()
    {
        $this->connections = [];
    }

    public function onOpen(\Brash\Websocket\Connection\Connection $connection): void
    {
        $this->connections[] = $connection;
    }

    public function handleTextData(string $data, \Brash\Websocket\Connection\Connection $connection): void
    {
        $connection->getLogger()->debug('IP'.':'.$connection->getIp().PHP_EOL);
        $connection->getLogger()->debug('Data: '.$data.PHP_EOL);
        $broadcast = array_filter($this->connections, fn ($conn) => $conn !== $connection);

        foreach ($broadcast as $conn) {
            $conn->writeText($data);
        }
        $connection->writeText($connection->getIp().'says: '.strtoupper($data));
    }
};

$middleware = $factory->create($connectionHandlerInterface);

$socket = new \React\Socket\SocketServer($argv[1] ?? '0.0.0.0:1337');

$server = new HttpServer($middleware);

$server->listen($socket);

echo 'Listening on '.str_replace('tcp:', 'http:', $socket->getAddress()).PHP_EOL;


use Brash\Websocket\Config\Config;


$factory = new MiddlewareFactory();
$factory->withConfig(new Config());


$factory = new MiddlewareFactory();
$factory->withParams([
    '/test'
]);

bash
php your_script.php [host:port]