PHP code example of dimogrudev / php-websocket

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

    

dimogrudev / php-websocket example snippets


use WebSocket\Server;
use WebSocket\Contract\ClientInterface;
use WebSocket\Contract\RequestInterface;
use WebSocket\Contract\MessageInterface;

0.0.0', 8443);
// Enable encryption and provide certificate files
$server->encryption(true, 'path/to/cert.crt', 'path/to/cert.key');

// Handle incoming messages and respond to clients
$server->onMessageReceive(function (ClientInterface $client, MessageInterface $message): void {
    if ($message->isBinary) {
        echo "{$client->ipAddr} (#{$client->id}) sends binary message ({$message->length} bytes)\n";

        // Echo the binary message back to the client
        $client->send($message->payload, isBinary: true);
    } else {
        echo "{$client->ipAddr} (#{$client->id}) sends `{$message->payload}`\n";

        // Reply with a text message
        $client->send("Server received your message: {$message->payload}");
    }
});

$server->start();

use WebSocket\Contract\DatagramInterface;

// Register a UDP listener to execute a function when a packet is received
// It provides listener ID which may be used for later cancellation
$listenerId = $server->listenUdp('127.0.0.1', 8600, function (DatagramInterface $packet): void {
    $payloadLength = strlen($packet->payload);
    echo "UDP packet received from {$packet->peer} ({$payloadLength} bytes)\n";

    // Reply back to the peer
    $packet->respond("Response data");
});

// Unregister and close the UDP listener
$server->closeUdp($listenerId);

// Create a timer to run function repeatedly with a 500 milliseconds interval
// It provides timer ID which may be used for later cancellation
$timerId = $server->setTimer(function (): void {
    // Your logic here
}, 500, true);

// Cancel the timer
$server->clearTimer($timerId);

$server->onHandshake(function (ClientInterface $client, RequestInterface $request): bool {
    // Reject connection if it's not from your trusted domain
    if ($request->header('origin') !== 'https://example.com') {
        return false;
    }
    return true;
});
bash
composer