欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[视频教程] 最新版swoole安装和TASKS功能测试

程序员文章站 2022-07-01 13:18:19
今天我们来安装和测试一下php的多并发高性能网络通信扩展,这个扩展是使用C语音开发的,加载到PHP以后,在PHP的层面上实现了多并发异步通信,模拟了go语音的很多特性,极大的拓宽了PHP的应用场景。 直接使用官网上的那句命令就可以,安装swoole时可能会出现错误和卡住不动,多试几次就能成功。pec ......

今天我们来安装和测试一下php的多并发高性能网络通信扩展,这个扩展是使用c语音开发的,加载到php以后,在php的层面上实现了多并发异步通信,模拟了go语音的很多特性,极大的拓宽了php的应用场景。

直接使用官网上的那句命令就可以,安装swoole时可能会出现错误和卡住不动,多试几次就能成功。
pecl install swoole
要配置php的cli环境和fpm环境的ini文件,把扩展的so加载进去。

视频地址:

httpserver.php

$http = new swoole_http_server("127.0.0.1", 9501);

$http->on("start", function ($server) {
        echo "swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function ($request, $response) {
        $response->header("content-type", "text/plain");
            $response->end("hello world\n");
});

$http->start();

注意使用httpclient的时候会有一些错误,首先新版的swoole移除了swoole\http\client,会报类找不到,其次要在协程中执行get方法

httpclient.php

$client = new swoole_client(swoole_sock_tcp, swoole_sock_async);
$client->on("connect", function($cli) {
	    $cli->send("hello world\n");
});
$client->on("receive", function($cli, $data){
	    echo "received: {$data}\n";
});
$client->on("error", function($cli){
	    echo "connect failed\n";
});
$client->on("close", function($cli){
	    echo "connection close\n";
});
$client->connect("127.0.0.1", 9502, 0.5);

taskserver.php

<?php
$serv = new swoole\server("127.0.0.1", 9502, swoole_base);

$serv->set(array(
    'worker_num' => 2,
    'task_worker_num' => 4,
));

$serv->on('receive', function(swoole\server $serv, $fd, $from_id, $data) {
    echo "接收数据" . $data . "\n";
    $data = trim($data);
    $task_id = $serv->task($data, 0); 
    $serv->send($fd, "分发任务,任务id为$task_id\n");
});

$serv->on('task', function (swoole\server $serv, $task_id, $from_id, $data) {
    echo "tasker进程接收到数据";
    echo "#{$serv->worker_id}\tontask: [pid={$serv->worker_pid}]: task_id=$task_id, data_len=".strlen($data).".".php_eol;
    $serv->finish($data);
});

$serv->on('finish', function (swoole\server $serv, $task_id, $data) {
    echo "task#$task_id finished, data_len=".strlen($data).php_eol;
});

$serv->on('workerstart', function($serv, $worker_id) {
    global $argv;
    if($worker_id >= $serv->setting['worker_num']) {
        swoole_set_process_name("php {$argv[0]}: task_worker");
    } else {
        swoole_set_process_name("php {$argv[0]}: worker");
    }
});

$serv->start();

  

taskclient.php

$client = new swoole_client(swoole_sock_tcp, swoole_sock_async);
$client->on("connect", function($cli) {
        $cli->send("hello world\n");
});
$client->on("receive", function($cli, $data){
        echo "received: {$data}\n";
});
$client->on("error", function($cli){
        echo "connect failed\n";
});
$client->on("close", function($cli){
        echo "connection close\n";
});
$client->connect("127.0.0.1", 9502, 0.5);