This package provides a PHP React/HTTP WebSocket Middleware.
Requires PHP 8.3+
This library provides a WebSocket message broadcasting solution using the ReactPHP library. It demonstrates how to handle incoming text messages, broadcast messages to other connected clients, and log connection details.
- PHP 8.3 or higher
- Composer
- ReactPHP
- Brash\Websocket library
-
Install the dependencies via Composer:
composer install
-
Ensure the autoloader is included:
require_once __DIR__.'/vendor/autoload.php';
Run the WebSocket server by executing the script in your terminal:
php your_script.php [host:port]
The AbstractTextMessageHandler
class handles WebSocket text messages. This implementation processes new connections, receives data, and broadcasts it to other connected clients.
Creates the middleware required for handling WebSocket connections.
Handles HTTP requests and integrates WebSocket middleware.
-
Connection Handling
- The server tracks all active connections in the
$connections
array. - When a new connection is established, it is added to the array using the
onOpen
method.
- The server tracks all active connections in the
-
Message Broadcasting
- When a client sends a message, it is logged using the connection’s logger.
- The message is broadcast to all other clients, except the sender.
- The sender receives a response that includes their IP address and the message content in uppercase.
Here is the core server implementation:
$connectionHandlerInterface = new class extends AbstractTextMessageHandler
{
private array $connections;
public function __construct()
{
$this->connections = [];
}
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);
}
$connection->writeText($connection->getIp().'says: '.strtoupper($data));
}
};
$middleware = $factory->create($connectionHandlerInterface);
$socket = new \React\Socket\SocketServer($argv[1] ?? '0.0.0.0:1337');
$server = new HttpServer($middleware);
$server->listen($socket);
echo 'Listening on '.str_replace('tcp:', 'http:', $socket->getAddress()).PHP_EOL;
When a client connects and sends a message:
- The server logs the IP address and message data.
- All other connected clients receive the message.
- The sender receives a response in uppercase:
Client 1 sends: Hello World
Client 2 receives: Hello World
Client 1 receives: 127.0.0.1 says: HELLO WORLD
It is optional to set a Config object in the MiddlewareFactory, but you can do it as:
use Brash\Websocket\Config\Config;
$factory = new MiddlewareFactory();
$factory->withConfig(new Config());
It is optional to set an array of paths, but this can be achieved as follows:
$factory = new MiddlewareFactory();
$factory->withParams([
'/test'
]);
This library is licensed under the MIT License. See the LICENSE
file for more details.
Contributions are welcome! Feel free to submit issues or pull requests on GitHub.
Enjoy using the WebSocket Message Broadcasting Library!