swow icon indicating copy to clipboard operation
swow copied to clipboard

http server 执行超时处理的困惑

Open smallslime opened this issue 3 years ago • 4 comments

server代码

declare(strict_types=1);

use Swow\Coroutine;
use Swow\Psr7\Server\Server;

require __DIR__ . '/../vendor/autoload.php';

$cos = new SplObjectStorage();

Coroutine::run(function() use ($cos){
    while (true) {
        foreach ($cos as $co) {
            /** @var Coroutine $co */
            if (!$co->isAlive()) {
                $cos->detach($co);
                continue;
            }
            if ($co->getElapsed() >= 800) {
                $cos->detach($co);
                $co->throw(new Exception("timeout!"));
            }
        }
        usleep(100 * 1000);
    }
});

$server = new Server();
$server->bind('127.0.0.1', 8000)->listen();

while (true) {
    $connection = $server->acceptConnection();
    $cos->attach(Coroutine::run(static function () use ($connection): void {
        try {
            sleep(2);
            $response = new \Swow\Psr7\Message\Response();
            $response->getBody()->write('ok');
            $connection->sendHttpResponse($response);
        } catch (Exception $e) {
            Coroutine::run(static function() use ($connection, $e): void{
                $response = (new \Swow\Psr7\Message\Response())->withStatus(500);
                $response->getBody()->write($e->getMessage());
                $connection->sendHttpResponse($response);
            });
        }
    }));
}

client代码:

$loopTime = 50;
$url = "http://127.0.0.1:8000/";

$wr = new \Swow\Sync\WaitReference();
for ($i=0;$i<$loopTime;$i++) {
    \Swow\Coroutine::run(function() use ($url, $wr){
        $h = curl_init($url);
        curl_setopt($h, CURLOPT_RETURNTRANSFER, 1);
        $rs = curl_exec($h);
        var_dump($rs);
    });
}
\Swow\Sync\WaitReference::wait($wr);

用client压server,期望返回50个timeout,但是多压几次,client总是会出现一些false,server 也没有 write socket 失败的warning(并且确认,$connection->sendHttpResponse() 都是有正常调用的。

如果是使用姿势问题,求助应该如何写?

image

smallslime avatar Feb 05 '23 05:02 smallslime

贴一下版本信息,没压出来问题

twose avatar Feb 05 '23 05:02 twose

image image image

系统是win11下 wsl2->ubuntu image

smallslime avatar Feb 05 '23 06:02 smallslime

没有复现,Apple M1 上的虚拟机不支持嵌套 Hyper-V,晚点我找个 Windows 电脑看看。

twose avatar Feb 06 '23 02:02 twose

cURL hook 做了一些优化,但不知道是否有关联,可以用最新版再试试。

twose avatar Mar 01 '23 04:03 twose