PHP code example of php-websocket-rpc / rpc-client

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

    

php-websocket-rpc / rpc-client example snippets


use PhpWebsocketRpc\RpcClient\Client\RpcClient;

$client = RpcClient::connect('ws://127.0.0.1:9502/rpc');

// ─── Using contract proxies ───

$math = $client->createProxy(MathService::class);

$result = $math->add(10, 5);               // call/response
echo $result;                               // 15

$math->log('Hello!');                       // notification

foreach ($math->count(10) as $value) {      // streaming
    echo $value;
}

$math->onEvent(function (string $event) {   // subscribe
    echo "Got: $event";
});

$chat->send('Hello!');                      // publish

use PhpWebsocketRpc\Rpc\Contract\AuthService;
use PhpWebsocketRpc\Rpc\Auth\User;

$auth = $client->createProxy(AuthService::class);
$user = $auth->authenticate('your-token-here');

// $user is a User object (implements WebsocketUserInterface)
echo $user->id;      // user identifier
echo $user->roles;   // ['customer', 'admin']

use PhpWebsocketRpc\Rpc\Exception\AuthenticationException;
use PhpWebsocketRpc\Rpc\Exception\AuthorizationException;

try {
    $user = $auth->authenticate('invalid-token');
} catch (AuthenticationException $e) {
    echo $e->getRpcCode();      // -32010
    echo $e->getMessage();      // 'Invalid or expired token'
}

try {
    $chat->deleteMessage('msg-1');  // 01 (METHOD_NOT_FOUND)
}

$auth->logout();  // clears auth state for this connection

interface MathService
{
    public function add(int $a, int $b): int;
    public function mul(int $a, int $b): int;
}

$math = $client->createProxy(MathService::class);
$sum = $math->add(10, 5);        // returns 15 — no boilerplate