1. Go to this page and download the library: Download brash/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/ */
brash / websocket example snippets
$server = new \Brash\Websocket\WsServer(host: '0.0.0.0', port: 1337);
$server->setConnectionHandler(
connectionHandlerInterface: new class extends \Brash\Websocket\Message\Protocols\AbstractTextMessageHandler {
private array $connections;
public function __construct()
{
$this->connections = [];
}
// Optional, as with on onDisconnect, onError
public function onOpen(\Brash\Websocket\Connection\Connection $connection): void
{
$this->connections[] = $connection;
}
public function handleTextData(string $data, \Brash\Websocket\Connection\Connection $connection): void
{
$connection->getLogger()->debug("IP" . ":" . $connection->getIp() . PHP_EOL);
$connection->getLogger()->debug("Data: " . $data . PHP_EOL);
$broadcast = array_filter($this->connections, fn($conn) => $conn !== $connection);
foreach ($broadcast as $conn) {
$conn->writeText($data);
}
}
}
);
$server->start();