如何在 reactPHP 服务器中保持状态?
How to keep state in reactPHP server?
到达 PHP 服务器。请求次数统计代码:
$counter = 0;
$app = function ($request, $response) use ($counter){
$response->writeHead(200, array('Content-Type' => 'text/plain'));
$response->end($counter);
$counter++;
};
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);
$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";
$socket->listen(1337);
$loop->run();
对于每个请求,计数器都保持为 0,我怎样才能使 $counter 变量对服务器的所有请求保持不变?
只需要在$counter前加上&-符号即可转账:
$counter = 0;
$app = function ($request, $response) use (&$counter){
$response->writeHead(200, array('Content-Type' => 'text/plain'));
$response->end($counter);
$counter++;
};
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);
$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";
$socket->listen(1337);
$loop->run();
傻我...
到达 PHP 服务器。请求次数统计代码:
$counter = 0;
$app = function ($request, $response) use ($counter){
$response->writeHead(200, array('Content-Type' => 'text/plain'));
$response->end($counter);
$counter++;
};
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);
$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";
$socket->listen(1337);
$loop->run();
对于每个请求,计数器都保持为 0,我怎样才能使 $counter 变量对服务器的所有请求保持不变?
只需要在$counter前加上&-符号即可转账:
$counter = 0;
$app = function ($request, $response) use (&$counter){
$response->writeHead(200, array('Content-Type' => 'text/plain'));
$response->end($counter);
$counter++;
};
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);
$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";
$socket->listen(1337);
$loop->run();
傻我...