(PECL event >= 1.4.0-beta)
EventHttp::setCallback — 为指定 URI 设置回调
path
要调用回调的路径。
cb
在请求的 path
上调用的回调 callable。它应该与以下原型匹配
req
EventHttpRequest 对象。
arg
自定义数据。
arg
自定义数据。
示例 #1 EventHttp::setCallback() 示例
<?php
/*
* 简单 HTTP 服务器。
*
* 测试方法:
* 1) 在您选择的端口上运行,例如:
* $ php examples/http.php 8010
* 2) 在另一个终端中连接到此端口上的某个地址
* 并发送 GET 或 POST 请求(此处已禁用其他请求),例如:
* $ nc -t 127.0.0.1 8010
* POST /about HTTP/1.0
* Content-Type: text/plain
* Content-Length: 4
* Connection: close
* (按下回车键)
*
* 它将输出
* a=12
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* 3) 查看服务器在之前终端窗口中的输出。
*/
function _http_dump($req, $data) {
static $counter = 0;
static $max_requests = 2;
if (++$counter >= $max_requests) {
echo "计数器达到最大请求数 $max_requests. 退出\n";
exit();
}
echo __METHOD__, " 被调用\n";
echo "请求:"; var_dump($req);
echo "数据:"; var_dump($data);
echo "\n===== 转储 =====\n";
echo "命令:", $req->getCommand(), PHP_EOL;
echo "URI:", $req->getUri(), PHP_EOL;
echo "输入报头:"; var_dump($req->getInputHeaders());
echo "输出报头:"; var_dump($req->getOutputHeaders());
echo "\n >> 发送回复 ...";
$req->sendReply(200, "OK");
echo "OK\n";
echo "\n >> 读取输入缓冲区 ...\n";
$buf = $req->getInputBuffer();
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
echo "缓冲区中没有更多数据\n";
}
function _http_about($req) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> 发送回复 ...";
$req->sendReply(200, "OK");
echo "OK\n";
}
function _http_default($req, $data) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> 发送回复 ...";
$req->sendReply(200, "OK");
echo "OK\n";
}
$port = 8010;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("无效的端口");
}
$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);
$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "自定义数据值");
$http->bind("0.0.0.0", 8010);
$base->loop();
?>
以上示例将输出类似于以下内容
a=12 HTTP/1.0 200 OK Content-Type: text/html; charset=ISO-8859-1 Connection: close