Created
May 8, 2019 13:31
-
-
Save RomanStone/f1d6160ef4c0b62da640aac473429884 to your computer and use it in GitHub Desktop.
PHP Events Simple Hello World Server Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$addr = '127.0.0.1'; | |
$port = 10080; | |
$host = 'localhost'; | |
function hello_world($args = array()) { | |
$OS = PHP_OS; //strtolower(substr(PHP_OS, 0, 3)) == 'win'; | |
$phpversion = phpversion(); | |
$resp = new stdClass(); | |
$resp->http_status = array('code' => 200, 'msg' => 'OK'); | |
$resp->http_headers = array('Content-Type' => 'text/html; charset=utf-8'); | |
$resp->http_body = '<!DOCTYPE HTML>' | |
. '<html>' | |
. '<head>' | |
. '<title>Hello World</title>' | |
. '</head>' | |
. '<body>' | |
. '<h1>Hello World!</h1>' | |
. "<h4>PECL Events PHP/{$phpversion} Sockets/{$OS}</h4>" | |
. '<pre>' . print_r($args, true) . '</pre>' | |
. '</body>' | |
. '</html>'; | |
$resp->http_headers['Content-Length'] = strlen($resp->http_body); | |
$resp->http_headers['Connection'] = 'close'; | |
$resp->http_headers['Server'] = "Events PHP/{$phpversion}"; | |
return $resp; | |
} | |
function _close_callback($conn = NULL) : void { | |
if ($conn) { | |
echo "."; | |
} | |
} | |
function _http_default($req = NULL, $arg = NULL) : void { | |
if ($req) { | |
$resp = hello_world(array( | |
'cmd' => $req->getCommand(), | |
'host' => $req->getHost(), | |
'path' => $req->getUri(), | |
'headers' => $req->getInputHeaders() | |
) | |
); | |
$conn = $req->getConnection(); | |
$conn->setCloseCallback('_close_callback', NULL); | |
$bev = $req->getBufferEvent(); | |
$bev->enable(Event::READ); | |
$buf = new EventBuffer(); | |
$buf->add($resp->http_body); | |
foreach($resp->http_headers as $key => $val) { | |
$req->addHeader($key, $val, EventHttpRequest::OUTPUT_HEADER); | |
} | |
$req->sendReply($resp->http_status['code'], $resp->http_status['msg']); | |
$req->sendReplyChunk($buf); | |
$req->sendReplyEnd(); | |
} | |
} | |
$base = new EventBase(); | |
$http = new EventHttp($base); | |
$http->setDefaultCallback('_http_default', NULL); | |
if (defined('SIGINT')) { | |
$signal = Event::signal($base, SIGINT, function() use($base) { | |
echo "Caught SIGINT\n"; | |
$base->stop(); | |
}); | |
$signal->add(); | |
} | |
$http->bind($addr, $port); | |
$http->addServerAlias($host); | |
$http->setAllowedMethods(EventHttpRequest::CMD_GET | |
| EventHttpRequest::CMD_POST | |
//| EventHttpRequest::CMD_OPTIONS | |
); | |
$http->setTimeout(60); | |
$base->loop(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ab -c 10000 -n 10000 http://127.0.0.1:10080/
CPU: AMD Phenom II X4 (945) Windows x64 | 0.723 [ms] / Request (Avg.)
PHP -V