swoole 写一个http
以下是一个基本的swoole http服务器示例:
<?php
$http = new \Swoole\Http\Server("0.0.0.0", 9501);
$http->on("start", function ($server) {
echo "Swoole http server is started at http://0.0.0.0:9501\n";
});
$http->on("request", function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World\n");
});
$http->start();
首先,我们创建了一个 Swoole\Http\Server 实例,指定了监听的地址和端口。
然后,我们为 start 和 request 事件分别注册了回调函数。
在 start 事件回调函数中,我们简单地输出了一条启动信息,告诉用户服务器已经启动。
在 request 事件回调函数中,我们设置了响应头的 Content-Type 为 text/plain,并输出了一个 Hello World 的字符串作为响应体。
最后,我们调用了 $http->start() 方法,启动了服务器。
运行代码后,访问 http://localhost:9501 可以看到输出的 Hello World 字符串。
原文地址: https://www.cveoy.top/t/topic/b2xU 著作权归作者所有。请勿转载和采集!