环境应用 Docker:

在 docker 中搭建 swoole 运行环境

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

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

测试程序代码:

<?phpuse 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.phpRequest num:5000Success num:5000Total time:2.9934Request per second:1670root@37a5ad8c277a:/var/www/project-1# php web/client.phpRequest num:5000Success num:5000Total time:3.4571Request per second:1446root@37a5ad8c277a:/var/www/project-1# php web/client.phpRequest num:5000Success num:5000Total time:2.6804Request per second:1865root@37a5ad8c277a:/var/www/project-1# php web/client.phpRequest num:5000Success num:5000Total time:2.8765Request per second:1738root@37a5ad8c277a:/var/www/project-1# php web/client.phpRequest num:5000Success num:5000Total time:2.3307Request per second:2145