react-websocket/examples/server.php

62 lines
2.3 KiB
PHP

<?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;
// The middleware is at the core, as it intercepts and breaks out the websocket
// connections received by the HttpServer.
$websockets = new WebSocketMiddleware();
// The 'connection' handler works like expected. You can't however write any data
// to the client yet, as the websocket streams have not yet been returned.
$websockets->on('connection', function (WebSocketInterface $websocket) {
// This just echoes text received, unless the websocket is part of a group.
// In this case the message is sent to all websockets in the group.
$websocket->on('text', function ($text) use ($websocket) {
// Send a message with the group name starting with '#' to join a group.
if (str_starts_with($text, '#')) {
$websocket->setGroup(substr($text,1));
$websocket->write("joined group {$text}");
} else {
// Echo back if not in group, send to group otherwise
if (!$websocket->getGroup())
$websocket->write($text);
else
foreach ($websocket->getGroup() as $member)
$member->write($text);
}
});
});
// Create the server with our middleware chain:
// error handler -> websocket handler -> http handler
$server = new HttpServer(
// Error handler
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);
});
},
// WebSocket handler
$websockets,
// HTTP handler
function (ServerRequestInterface $request) {
return Response::plaintext("Hello world!");
}
);
// Everything else is as expected!
$socket = new SocketServer("tcp://0.0.0.0:8000");
$server->listen($socket);