php网络编程swoole http

服务端:

<?php
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;

// 创建 HTTP 服务器
$server = new Server('127.0.0.1', 9501);

$server->on('start', function ($server) {
    //print_r($server);
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});
    
// 设置服务器配置
$server->set([
    'worker_num' => 4, // 设置工作进程数
    'max_request' => 1000, // 每个进程最大接受请求数
    'dispatch_mode' => 1, // 数据包分发策略
    "enable_static_handler"    => true,  //支持静态文件
    "document_root"   => "D:/workspace/swoole_test/static",//文件位置
    'daemonize'=> false,
]);

// 监听请求事件
$server->on('request', function (Request $request, Response $response) {
    echo "get:\n".print_r($request->get, true)."\n\n";
    echo "post:\n".print_r($request->post, true)."\n\n";
    echo "cookie:\n".print_r($request->cookie, true)."\n\n";
    echo "files:\n".print_r($request->files, true)."\n\n";
    echo "header:\n".print_r($request->header, true)."\n\n";
    echo "server:\n".print_r($request->server, true)."\n\n";
    
    // 设置响应头
    $response->header('Content-Type', 'text/html; charset=utf-8');
    $response->cookie("User", "Swoole");
    $response->header("X-Server", "Swoole");
    
    // 处理 GET 请求
    if ($request->server['request_method'] == 'GET') {
        $response->end('你好,我是Swoole');
    } else {
        $response->end('Method Not Allowed');
    }
});
    
// 启动服务器
$server->start();

  客户端:

<?php
use Swoole\Coroutine\Http\Client;
use function Swoole\Coroutine\run;

run(function () {
    $cli = new Client('127.0.0.1', 9501);
    $cli->get('/get');
    echo $cli->body;
    $cli->close();
});

  

输出:

 

posted @ 2024-12-23 20:34  河北大学-徐小波  阅读(6)  评论(0编辑  收藏  举报