react-websocket/examples/server.php

61 lines
2.2 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;
2024-02-23 23:15:57 +00:00
// The middleware is at the core, as it intercepts and breaks out the websocket
// connections received by the HttpServer.
2024-02-21 02:03:08 +00:00
$websockets = new WebSocketMiddleware();
2024-02-23 23:15:57 +00:00
// 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.
2024-02-21 20:40:29 +00:00
$websockets->on('connection', function (WebSocketInterface $websocket) {
2024-02-23 23:15:57 +00:00
// 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.
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);
}
}
});
});
2024-02-23 23:15:57 +00:00
// Create the server with our middleware chain:
// error handler -> websocket handler -> http handler
2024-02-21 02:03:08 +00:00
$server = new HttpServer(
2024-02-23 23:15:57 +00:00
// Error handler
2024-02-21 02:03:08 +00:00
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);
});
},
2024-02-23 23:15:57 +00:00
// WebSocket handler
$websockets,
// HTTP handler
2024-02-21 02:03:08 +00:00
function (ServerRequestInterface $request) {
return Response::plaintext("Hello world!");
}
);
2024-02-23 23:15:57 +00:00
// Everything else is as expected!
2024-02-21 02:03:08 +00:00
$socket = new SocketServer("tcp://0.0.0.0:8000");
2024-02-23 23:15:57 +00:00
$server->listen($socket);