PHP code example of venndev / vosaka-wsock

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

    

venndev / vosaka-wsock example snippets


use vosaka\wsock\connection\Connection;
use vosaka\wsock\connection\Message;
use vosaka\wsock\server\AbstractWebSocketHandler;
use vosaka\wsock\server\ServerConfig;
use vosaka\wsock\server\WebSocketServer;
use vosaka\wsock\connection\ConnectionRegistry;
use vosaka\foroutines\RunBlocking;
use function vosaka\foroutines\main;

final class ChatHandler extends AbstractWebSocketHandler {
    public function onOpen(Connection $connection): void {
        echo "New connection: {$connection->id}\n";
        $connection->sendText("Welcome to the server!");
    }

    public function onMessage(Connection $connection, Message $message): void {
        if ($message->isText()) {
            echo "Message from {$connection->id}: {$message->getContent()}\n";
            $connection->sendText("Echo: " . $message->getContent());
        }
    }
}

main(function () {
    RunBlocking::new(function () {
        $config = new ServerConfig(host: '0.0.0.0', port: 9000);
        $registry = new ConnectionRegistry();
        $server = new WebSocketServer(
            config: $config,
            handler: new ChatHandler($registry),
            registry: $registry
        );

        $server->start();
        echo "WebSocket server started on ws://localhost:9000\n";
    });
});