PHP code example of reactphp-x / websocket-middleware
1. Go to this page and download the library: Download reactphp-x/websocket-middleware 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/ */
reactphp-x / websocket-middleware example snippets
eactphpX\WebsocketMiddleware\WebsocketMiddleware;
use Psr\Http\Message\ServerRequestInterface;
use ReactphpX\WebsocketMiddleware\ConnectionInterface;
use ReactphpX\WebsocketMiddleware\MessageComponentInterface;
/**
* chat.php
* Send any incoming messages to all connected clients (except sender)
*/
class MyChat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn, ServerRequestInterface $request) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from != $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn, $reason = null) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$http = new React\Http\HttpServer(new WebsocketMiddleware(new MyChat()));
$socket = new React\Socket\SocketServer('0.0.0.0:8090');
$http->listen($socket);
eactphpX\WebsocketMiddleware\WebsocketMiddleware;
use ReactphpX\WebsocketMiddleware\EchoServer;
$http = new React\Http\HttpServer(new WebsocketMiddleware(new EchoServer()));
$socket = new React\Socket\SocketServer('0.0.0.0:8090');
$http->listen($socket);
eactphpX\WebsocketMiddleware\WebsocketMiddleware;
use ReactphpX\WebsocketMiddleware\EchoServer;
putenv("X_LISTEN=0.0.0.0:8090");
$app = new \FrameworkX\App();
$app->get('/echo', new WebsocketMiddleware(new EchoServer()));
$app->run();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.