swoole--协程HTTP服务器

2021-05-23

不是Co\Server的子类,与 Http\Server 的不同之处:

  1. 可以在运行时动态地创建、销毁
  2. 对连接的处理是在单独的子协程中完成,客户端连接的 Connect、Request、Response、Close 是完全串行的
use Swoole\Coroutine\Server;
use function Swoole\Coroutine\run;


run(function () {
	// 创建监听$host、$port的服务,$ssl为true时启用ssl,$reuse_port为true启动端口重用
   	$server = new Server($host, $port = 0, $ssl = false, $reuse_port = false);

   	// 注册回调函数以处理参数$pattern所指示路径下的HTTP请求,$pattern为URL,不能传入http://domain
   	$server->handle($pattern = '/', function ($request, $response) {
        $response->end("<h1>Index</h1>");
    });
    $server->handle($pattern = '/test', function ($request, $response) {
        $response->end("<h1>Test</h1>");
    });
    $server->handle($pattern = '/stop', function ($request, $response) use ($server) {
        $response->end("<h1>Stop</h1>");
        // 终止服务器
        $server->shutdown();
    });

    // 启动服务器
    $server->start();
});

 

{/if}