1. Go to this page and download the library: Download ez-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/ */
ez-php / websocket example snippets
use EzPhp\WebSocket\ChannelManager;
use EzPhp\WebSocket\ConnectionInterface;
use EzPhp\WebSocket\Frame;
use EzPhp\WebSocket\HandlerInterface;
use EzPhp\WebSocket\Server;
class ChatHandler implements HandlerInterface
{
public function __construct(private readonly ChannelManager $channels) {}
public function onOpen(ConnectionInterface $conn): void
{
$this->channels->subscribe('general', $conn);
$this->channels->broadcast('general', "{$conn->id()} joined.");
}
public function onMessage(ConnectionInterface $conn, Frame $frame): void
{
$this->channels->broadcast('general', "[{$conn->id()}] {$frame->payload}");
}
public function onClose(ConnectionInterface $conn): void
{
$this->channels->unsubscribeAll($conn);
$this->channels->broadcast('general', "{$conn->id()} left.");
}
public function onError(ConnectionInterface $conn, \Throwable $e): void
{
error_log("WebSocket error [{$conn->id()}]: {$e->getMessage()}");
}
}
$server = new Server('0.0.0.0', 8080);
$server->run(new ChatHandler(new ChannelManager()));
$conn->id(); // unique string ID assigned by Server
$conn->isConnected(); // false after close() or peer disconnect
$conn->send('text'); // UTF-8 TEXT frame
$conn->sendBinary($b); // BINARY frame
$conn->close('bye'); // clean close with status 1000
$mgr->subscribe('room', $conn);
$mgr->unsubscribe('room', $conn);
$mgr->unsubscribeAll($conn); // called in onClose()
$mgr->broadcast('room', 'message'); // sends TEXT frame to all connected subscribers
$mgr->connections('room'); // list<ConnectionInterface>
$mgr->channels(); // list<string>
$mgr->count('room'); // int
bash
composer
bash
php chat-server.php
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.