前提要先安装php的swoole扩展
共两个文件http.php与user.php,两个在同一个文件夹下
http.php代如下:
<?php
use server\Task;
class Http {
const HOST = '0.0.0.0';
const PORT = 9501;
private $http = null;
public function __construct() {
$this->http = new Swoole\Http\Server(self::HOST, self::PORT);
$this->http->set(self::config());
$this->http->on("request", [$this, "onRequest"]);
$this->http->on('Task', [$this, 'onTask']);
$this->http->on('finish', [$this, 'onFinish']);
$this->http->start();
}
private function config()
{
return [
"enable_static_handler" => true, //开启静态资源访问
"document_root" => "/Users/johnson/WorkRoom/Project/live.csm.com/uniapp/", //访问的根目录
'worker_num' => 4, //配置为cpu个数的1-4倍"
'task_worker_num' => 4,
//"open_http_protocol" => true,
//"ssl_cert_file" => "",
//"ssl_key_file"=>"",
];
}
public function onRequest($request, $response) {
//使用 Chrome 浏览器访问服务器,会产生额外的一次请求,/favicon.ico,可以在代码中响应 404 错误
if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
$response->end();
return;
}
//
$response->header('Content-Type', 'text/html; charset=utf-8');
$reg_file = $request->server["request_uri"];
//让其它php页面可以拿到$this->http
$_SERVER['http'] = $this->http;
//
$file_path = __DIR__ . $reg_file;
$res = '';
if (file_exists($file_path))
{
ob_start();
include $file_path;
$res = ob_get_contents();
ob_end_clean();
}
$response->end($res);
}
public function onTask($serv, $task_id, $reactor_id, $data) {
require_once __DIR__ . '/task.php';
$obj = new Task();
$method = $data['method'];
$res = $obj->$method($data['data'], $serv);
//sleep(5);
return "task finish";
}
public function onFinish($serv, $task_id, $data)
{
echo "AsyncTask[{$task_id}] Finish: {$data}".PHP_EOL;
}
}
new Http();
user.php代码如下
<?php
echo "hello,johnson".PHP_EOL;
$task_data = [
'method' => 'sendSms',
'data' => [
'phone' => '13950909098',
'code' => '1234'
]
];
$_SERVER['http']->task($task_data);
命令行里执行 php http.php 开启swoole的http服务
在浏览器里运行 http://localhost:9501/user.php 就可以看到输出的内容,切换到命令行也能看到异步任务输出的内容