PHP code example of yaknet / websocket

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

    

yaknet / websocket example snippets




use YakNet\WebSocket\Connection;
use YakNet\WebSocket\Contract\ConnectionHandlerInterface;

class MyChatHandler implements ConnectionHandlerInterface
{
    public function onOpen(Connection $connection): void
    {
        echo "✔ Connection established: {$connection->getId()} from {$connection->getRemoteAddress()}\n";
        $connection->send("Welcome to the real-time hub!");
    }

    public function onMessage(Connection $connection, string $message): void
    {
        echo "✉ Message received: {$message}\n";
        // Echo response back to client
        $connection->send("Echo: " . $message);
    }

    public function onClose(Connection $connection, int $code, string $reason): void
    {
        echo "✖ Connection closed: {$connection->getId()} (Code: {$code}, Reason: {$reason})\n";
    }

    public function onError(Connection $connection, \Throwable $exception): void
    {
        echo "⚠ Error: " . $exception->getMessage() . "\n";
    }
}



akNet\WebSocket\Server;

$server = new Server('0.0.0.0', 8090, new MyChatHandler());

echo "WebSocket Server running on ws://0.0.0.0:8090...\n";
$server->start();

$sslOptions = [
    'local_cert' => '/path/to/fullchain.pem',
    'local_pk'   => '/path/to/privkey.pem',
    'verify_peer' => false,
];

// Passing SSL options automatically switches server to secure protocols
$server = new Server('0.0.0.0', 8090, new MyChatHandler(), $sslOptions);
$server->start();



akNet\WebSocket\Client;

try {
    $client = new Client('ws://localhost:8090');
    $client->connect();

    // Sends a masked text frame (RFC compliant)
    $client->send('Hello Server!');

    // Receive message (Wait up to 2 seconds)
    $frame = $client->receive(2.0);
    if ($frame) {
        echo "Server response: " . $frame->getPayload() . "\n";
    }

    // Clean connection closure
    $client->close();
} catch (\Throwable $e) {
    echo "Client Error: " . $e->getMessage() . "\n";
}