1. Go to this page and download the library: Download timostamm/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/ */
timostamm / websocket-server example snippets
$loop = Factory::create(); // use a react event loop
// start server
$server = new WebsocketServer($loop, [
'uri' => '127.0.0.1:23080'
]);
// add a controller
$server->route([
'match' => '/example/*',
'controller' => new class() implements ControllerInterface
{
function onOpen(WebSocket $connection): void
{
print $connection . ' connected. Sending a "Hello".' . PHP_EOL;
$connection->send('Hello');
}
function onMessage(WebSocket $from, string $payload, bool $binary): void
{
print $from . ' sent: ' . $payload . PHP_EOL;
}
function onClose(WebSocket $connection, ?Throwable $error): void
{
print $connection . ' disconnected.' . PHP_EOL;
}
}
]);
// This error handler will be called when an exception was thrown
// by a filter, a controller method or the underlying tcp server.
$server->on('error', function (Throwable $error) {
print 'Server error: ' . $error->getMessage() . PHP_EOL;
});
$loop->run(); // the react event loop processes socket connections