三十六、Swoole 基础学习笔记 - Swoole 协程 HTTP 服务器
hi,我是温新,一名PHPer
文章基于 Swoole 5.0.1 版本编写。
学习目标:学习协程 HTTP 服务器
说明:本篇文章结合官方文档编写及参考网络资料编写,虽非全部原创,但也是结合了自己的理解,若转载请附带本文 URL,编写不易,持续编写更不易,谢谢!
完全协程化的 HTTP 服务器实现,Co\Http\Server
由于 HTTP 解析性能原因使用 C++ 编写,因此并非由 PHP 编写的 Co\Server 的子类。
与 Http\Server的不同之处:
1、可以在运行时动态地创建、销毁;
2、对连接的处理是在单独的子协程中完成,客户端连接的 Connect
、Request
、Response
、Close
是完全串行的。
协程 HTTP 案例
<?php
// 36-swoole-coroutine-http-server.php
Swoole\Coroutine\run(function () {
$http = new Swoole\Coroutine\Http\Server('0.0.0.0', 9501, false);
$http->handle('/', function ($request, $response) {
$response->end("<h1>Index</h1>");
});
$http->handle('/test', function ($request, $response) {
$response->end("<h1>Test</h1>");
});
$http->handle('/stop', function ($request, $response) use ($http) {
$response->end("<h1>Stop</h1>");
$http->shutdown();
});
$http->start();
});
协程 HTTP API
__construct
含义:构造函数。
语法:
Swoole\Coroutine\Http\Server::__construct(string $host, int $port = 0, bool $ssl = false, bool $reuse_port = false);
handle
含义:注册回调函数以处理参数 $pattern
所指示路径下的 HTTP 请求。
语法:
Swoole\Coroutine\Http\Server->handle(string $pattern, callable $fn): void
# 参数
$pattern:设置 URL 路径【如 /index.html,注意这里不能传入 http://domain】;
$fn:处理函数,用法参考 Swoole\Http\Server 中的 OnReqeust。
start
含义:启动服务器。
shutdown
含义:关闭服务器。
我是温新,本篇文章结束。
请登录后再评论