PHP code example of krzysztofzylka / websocket

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

    

krzysztofzylka / websocket example snippets




use Async\EventLoop;
use Websocket\Connection;
use Websocket\Server;


    'adaptive_text_streaming' => true,
    'max_decompression_ratio' => 25,
]);
$server->setAllowedOrigins(['http://localhost:3000', 'file://', 'null'], false);
$server->setAuthValidator(static function (Connection $connection, array $headers, array $query): bool {
    return hash_equals('secret-token', $query['token'] ?? '');
});
$server->enableLogging(true);
$server->setAdaptiveMemoryTarget(64 * 1024 * 1024, 8 * 1024 * 1024);

$server->onOpen(function (Connection $connection): void {
    $connection->setProperty('user_id', 123);
    $connection->setLabel('authenticated-user');

    $connection->sendText('Welcome! Your connection id is ' . $connection->getId());
});

$server->onMessage(function (Connection $connection, string $payload, bool $isText): void {
    if ($isText) {
        $userId = $connection->getProperty('user_id');
        $connection->sendText(sprintf('[echo][user:%s] %s', $userId ?? 'guest', $payload));
    }
});

$server->start();
$loop->run();

$context = [
    'ssl' => [
        'local_cert' => __DIR__ . '/cert.pem',
        'local_pk' => __DIR__ . '/privkey.pem',
        'allow_self_signed' => true,
        'verify_peer' => false,
    ],
];

$options = [
    'tls' => true,
    'tls_auto_reload' => true,
    'tls_reload_interval' => 300,
];

$server = new Server($loop, '0.0.0.0', 8443, $context, $options);
$server->enableTlsAutoReload(true, 600); // równoważne ustawieniom w $options
$server->start();

$server->enableCompression(true); // domyślnie true
$server->setCompressionContextTakeover(clientNoContext: true, serverNoContext: true);
$server->setCompressionMinBytes(256); // minimalny rozmiar danych do kompresji

$server->setBinaryStreamThreshold(256 * 1024); // próg przełączenia na strumień
$server->setTextStreamThreshold(128 * 1024);   // osobny próg dla tekstu
$server->enableAdaptiveTextStreaming(true);    // dostosuj próg na podstawie pamięci
$server->setMaxMessageSize(8 * 1024 * 1024);  // globalny limit rozmiaru wiadomości

$server->onBinaryStream(function (Connection $connection, $stream, int $length): void {
    echo "[binary] {$length} bytes" . PHP_EOL;
    stream_copy_to_stream($stream, fopen('php://output', 'wb'));
    fclose($stream);
});

$server->setAllowedOrigins(['https://example.com'], true); // domyślnie wymaga nagłówka Origin zgodnego z listą
$server->setAuthValidator(static function (Connection $connection, array $headers, array $query): bool {
    return hash_equals('super-secret', $query['token'] ?? '');
});
$server->enableLogging(true); // opcjonalnie, by śledzić handshake i wiadomości
$server->setMaxDecompressionRatio(25.0); // ochrona przed zip bomb

$server->setMaxConnections(200);          // null = brak limitu
$server->setConnectionQueueLimit(100);    // 0 = brak limitu kolejki

echo 'Pending: ' . $server->getPendingConnectionCount();

$server->onOpen(function (Connection $connection) use ($userService): void {
    $token = $connection->getQueryParameter('token');
    if ($token !== null && ($userId = $userService->resolve($token))) {
        $connection->setProperty('user_id', $userId);
        $connection->setLabel('user:' . $userId);
    }
});

$server->onMessage(function (Connection $connection, string $payload, bool $isText) {
    $userId = $connection->getProperty('user_id', 'guest');
    printf("[%s] %s\n", $connection->getId(), $payload);
});

foreach ($server->getConnections() as $connection) {
    echo $connection->getLabel() ?? $connection->getId();
}

// znajdź połączenia po etykiecie lub właściwości
$admins = $server->findConnectionsByLabel('user:admin');
$user123 = $server->findConnectionsByProperty('user_id', 123);

foreach ($user123 as $conn) {
    $conn->sendText('Personalized notification');
}

$stats = $server->getStats();
print_r($stats);

// W razie potrzeby:
$server->resetStats();
bash
   php example/server.php
   
bash
php -l src/Frame.php
php -l src/Connection.php
php -l src/Server.php