Skip to content

Instantly share code, notes, and snippets.

@IvanChepurnyi
Created September 8, 2016 14:38
Show Gist options
  • Save IvanChepurnyi/1b28b77c019674becca3f96a6fa66983 to your computer and use it in GitHub Desktop.
Save IvanChepurnyi/1b28b77c019674becca3f96a6fa66983 to your computer and use it in GitHub Desktop.
Sample counter server in ReactPHP
<?php
require 'vendor/autoload.php';
$counter = new stdClass();
$counter->counter = 100000;
$counter->requests = 0;
$app = function ($request, $response) use ($counter) {
if ($request->getPath() === '/favicon.ico') {
$response->writeHead(404, array('Content-Type' => 'text/plain'));
} else {
$response->writeHead(200, array('Content-Type' => 'text/plain'));
}
$counter->requests ++;
switch ($request->getPath()) {
case '/dec':
$counter->counter --;
$response->end('Stock decreased');
break;
case '/info':
$response->write('Memory usage: ' . round(memory_get_usage()/(1024*1024), 4). "M\n");
$response->write('Requests processed: ' . $counter->requests . "\n");
$response->write('Current counter value: ' . $counter->counter . "\n");
$response->end();
break;
default:
$response->end('Current counter value: ' . $counter->counter . "\n");
break;
}
};
$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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment