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




// Create an instance of the server class
// 0.0.0.0 is set as host to make the server reachable at all IPv4 addresses
$server = new WebSocket\Server('0.0.0.0', 8443);
// Enable encryption and provide certificate files
$server->encryption(true, '../example_le1.crt', '../example_le1.key');

// Print the number of users online every 30 seconds
$server->setTimer(function () use ($server): void {
    print "Current online: {$server->online} user(s)\n";
}, 30000, true);
// Handle incoming messages
$server->onMessageReceive(function ($client, $message): void {
    if ($message->binary) {
        print "{$client->ipAddr} (#{$client->id}) sends binary message ({$message->length} bytes)\n";
    } else {
        print "{$client->ipAddr} (#{$client->id}) sends `{$message->payload}`\n";
    }
});

$server->start();

// 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 {}, 500, true);
// Cancel the timer
$server->clearTimer($timerId);

// Server starts
$server->onServerStart(function (): void {});
// Server stops
$server->onServerStop(function(): void {});
// Client establishes connection and sends handshake request
// Return TRUE to accept the request or FALSE to reject it and disconnect the client
$server->onClientConnect(function ($client, $request): bool {});
// Client disconnects
$server->onClientDisconnect(function ($client): void {});
// Client sends message
$server->onMessageReceive(function ($client, $message): void {});
cmd
composer