关于swoole:利用-Swoole-的-Channel-测试-Websocket-异步服务器性能

6次阅读

共计 1730 个字符,预计需要花费 5 分钟才能阅读完成。

环境应用 Docker:

在 docker 中搭建 swoole 运行环境

服务器端应用后面文章中的代码:

在 Swoole 中应用 WebSocket 服务端和客户端

测试程序代码:

<?php

use Swoole\Coroutine\Channel;
use Swoole\Coroutine\Http\Client;
use function Swoole\Coroutine\run;

class Test
{
    protected $request;     // 总申请量
    protected $requested = 0;
    protected $start_time;
    protected $channel;

    function __construct()
    {
        $this->request = 5000;
        $this->channel = new Channel($this->request);
    }

    public function run()
    {$this->start_time = microtime(true);
        $this->webSocket();}

    protected function webSocket()
    {
        // 创立一个协程容器
        run(function () {for ($i = 0; $i < $this->request; $i++) {
                // 开启一个协程
                go(function() use ($i) {$cli = new Client('127.0.0.1', 8081);
                    $cli->set(['websocket_mask' => false]);
                    $ret = $cli->upgrade('/');
                    if ($ret) {$ret = $cli->push('1 Hello World');
                        $this->channel->push([$i => $cli->recv(1)]);
                    }
                });
            }
            $this->finish();});
    }

    protected function finish()
    {for ($i = 1; $i <= $this->request; $i++) {$this->channel->pop();
            $this->requested++;
        }

        $cost_time = round(microtime(true) - $this->start_time, 4);
        echo "Request num:" . $this->request.PHP_EOL;
        echo "Success num:" . $this->requested.PHP_EOL;
        echo "Total time:"  . $cost_time.PHP_EOL;
        echo "Request per second:" . intval($this->request / $cost_time).PHP_EOL;
    }
}

$test = new Test();
$test->run();

测试后果:

root@37a5ad8c277a:/var/www/project-1# php web/client.php
Request num:5000
Success num:5000
Total time:2.9934
Request per second:1670
root@37a5ad8c277a:/var/www/project-1# php web/client.php
Request num:5000
Success num:5000
Total time:3.4571
Request per second:1446
root@37a5ad8c277a:/var/www/project-1# php web/client.php
Request num:5000
Success num:5000
Total time:2.6804
Request per second:1865
root@37a5ad8c277a:/var/www/project-1# php web/client.php
Request num:5000
Success num:5000
Total time:2.8765
Request per second:1738
root@37a5ad8c277a:/var/www/project-1# php web/client.php
Request num:5000
Success num:5000
Total time:2.3307
Request per second:2145
正文完
 0