Initial commit
This commit is contained in:
49
examples/server.php
Normal file
49
examples/server.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?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();
|
||||
$websockets->on('connect', function (WebSocketInterface $websocket) {
|
||||
$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);
|
Reference in New Issue
Block a user