PHP code example of brash / websocket

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




$server = new \Brash\Websocket\WsServer(host: '0.0.0.0', port: 1337);

$server->setConnectionHandler(
    connectionHandlerInterface: new class extends \Brash\Websocket\Message\Protocols\AbstractTextMessageHandler {

    private array $connections;

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

    // Optional, as with on onDisconnect, onError
    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);
        }
    }
    }
);
$server->start();

$configArray = [
    'timeout' => 5, // In seconds
    'maxPayloadSize' => 524288, //(0.5MiB)
    'maxMessagesBuffering' => 100, // 5mb in messages
    'writeMasked' => false,
    'prod' => true,
    'ssl' => false,
    'certFile' => '',
    'passphrase' => '',
    'sslContextOptions' => [],
];

$config = \Brash\Websocket\Config\Config::createFromArray($configArray);

// OR
$config = new \Brash\Websocket\Config\Config(
    // DEFAULTS: int $timeout = self::MESSAGE_TIMEOUT_IN_SECONDS,
    // DEFAULTS: int $maxPayloadSize = self::MAX_PAYLOAD_SIZE,
    // DEFAULTS: int $maxMessagesBuffering = self::MAX_MESSAGES_BUFFERING,
    // DEFAULTS: bool $writeMasked = false,
    // DEFAULTS: bool $prod = true,
    // DEFAULTS: ?\Brash\Websocket\Config\SslConfig $sslConfig = null
);

$server = new \Brash\Websocket\WsServer(host: '0.0.0.0', port: 1337, $config);


$server = new \Brash\Websocket\WsServer(9001, '127.0.0.1',
    new Config(
        ...[
            'ssl' => true,
            'certFile' => 'path/to/certificate/cert.pem',
            'sslContextOptions' => [
                'verify_peer' => false,
                'allow_self_signed' => true
            ]
        ]
    )
);