react-websocket/examples/server.php

49 lines
1.5 KiB
PHP
Raw Normal View History

2024-02-21 02:03:08 +00:00
<?php
require_once __DIR__."/../vendor/autoload.php";
use NoccyLabs\React\WebSocket\WebSocketInterface;
use NoccyLabs\React\WebSocket\WebSocketMiddleware;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\HttpServer;
use React\Http\Message\Response;
use React\Promise\Promise;
use React\Socket\SocketServer;
$websockets = new WebSocketMiddleware();
2024-02-21 20:40:29 +00:00
$websockets->on('connection', function (WebSocketInterface $websocket) {
2024-02-21 02:03:08 +00:00
$websocket->on('text', function ($text) use ($websocket) {
if (str_starts_with($text, '#')) {
$websocket->setGroup(substr($text,1));
$websocket->write("joined group {$text}");
} else {
if (!$websocket->getGroup())
$websocket->write($text);
else
foreach ($websocket->getGroup() as $member) {
$member->write($text);
}
}
});
});
$server = new HttpServer(
$websockets,
function (ServerRequestInterface $request, callable $next) {
$promise = new Promise(function ($resolve) use ($next, $request) {
$resolve($next($request));
});
return $promise->then(null, function (Exception $e) {
return Response::plaintext(
'Internal error: ' . $e->getMessage() . "\n"
)->withStatus(Response::STATUS_INTERNAL_SERVER_ERROR);
});
},
function (ServerRequestInterface $request) {
return Response::plaintext("Hello world!");
}
);
$socket = new SocketServer("tcp://0.0.0.0:8000");
$server->listen($socket);