PHP code example of webnarmin / amphp-websocket-server

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

    

webnarmin / amphp-websocket-server example snippets


use webnarmin\AmphpWS\WebSocketServer;
use webnarmin\AmphpWS\Contracts\WebsocketUser;

class MyWebSocketServer extends WebSocketServer
{
    protected function handleEcho(WebsocketUser $user, array $payload): array
    {
        return ['message' => 'Echo: ' . $payload['message']];
    }

    protected function handleSum(WebsocketUser $user, array $payload): array
    {
        $numbers = $payload['numbers'] ?? [];
        $sum = array_sum($numbers);
        return ['result' => $sum];
    }
}

use webnarmin\AmphpWS\Configurator;
use webnarmin\AmphpWS\Simple\SimpleAuthenticator;
use webnarmin\Cryptor\Cryptor;

$config = [
    'websocket' => ['host' => '127.0.0.1', 'port' => 1337],
    'allow_origins' => ['http://127.0.0.1:8000', 'http://localhost:8000'],
];
$configurator = new Configurator($config);
$cryptor = new Cryptor('your-private-key');
$authenticator = new SimpleAuthenticator('control-http-auth-token', $cryptor);

$server = new MyWebSocketServer($configurator, $authenticator);
$server->run();

class MyWebSocketServer extends WebSocketServer
{
    protected function handleEcho(WebsocketUser $user, array $payload): array
    {
        return ['message' => 'Echo: ' . $payload['message']];
    }

    protected function handleSum(WebsocketUser $user, array $payload): array
    {
        $numbers = $payload['numbers'] ?? [];
        $sum = array_sum($numbers);
        return ['result' => $sum];
    }
}

use webnarmin\Cryptor\Cryptor;

$cryptor = new Cryptor('websocket-private-key');
$publicKey = 'websocket-public-key';

$userId = time(); // Or any unique user identifier
$websocketToken = $cryptor->encrypt($userId, $publicKey);


use GuzzleHttp\Client;
use webnarmin\AmphpWS\WebsocketControlHttpClient;
use Psr\Log\NullLogger;

lient instance
$httpClient = new Client([
    'base_uri' => $baseUri,
    'headers' => [
        'Authorization' => $authToken,
        'Content-Type' => 'application/json',
    ],
]);

$client = new WebsocketControlHttpClient($httpClient, new NullLogger());

// Send a broadcast message
$success = $client->broadcastText('Hello, everyone!');

if ($success) {
    echo "Message broadcasted successfully.";
} else {
    echo "Failed to broadcast message.";
}

// Send a targeted message
$success = $client->sendText(1, 'Hello, User 1!');

if ($success) {
    echo "Message sent to user 1 successfully.";
} else {
    echo "Failed to send message to user 1.";
}

// Send a binary broadcast message
$binaryData = file_get_contents('path/to/file');
$success = $client->broadcastBinary($binaryData);

if ($success) {
    echo "Binary data broadcasted successfully.";
} else {
    echo "Failed to broadcast binary data.";
}

// Multicast a text message
$success = $client->multicastText('Hello, selected users!', [1, 2, 3]);

if ($success) {
    echo "Multicast message sent successfully.";
} else {
    echo "Failed to send multicast message.";
}

// Multicast a binary message
$binaryData = file_get_contents('path/to/file');
$success = $client->multicastBinary($binaryData, [1, 2, 3]);

if ($success) {
    echo "Binary data multicast successfully.";
} else {
    echo "Failed to multicast binary data.";
}

$config = [
    'websocket' => [
        'host' => '127.0.0.1',
        'port' => 1337,
        'use_ssl' => false,
        'ssl_cert' => null,
        'ssl_key' => null,
    ],
    'allow_origins' => ['*'],
    'max_connections' => 1000,
    'max_connections_per_ip' => 10,
    'timeout' => 60,
];

$configurator = new Configurator($config);