目录结构:
thinkphp5 swoole 执行异步任务_第1张图片
服务器端:

/
author:hdj
*/
namespace app\Console;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Websocket extends Command{
protected $server;
protected function configure()
{
$this->setName('websocket:start')->setDescription('Start Web Socket Server!');
}
protected function execute(Input $input, Output $output)
{
$serv = new \swoole_server('0.0.0.0',9501);

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

$serv->on('connect', function ($serv, $fd){
echo $fd."客户端已经连接进来了.\n";
});
$serv->on('receive', function($serv, $fd, $from_id, $data) {
$task_id = $serv->task($data);
echo "开始投递异步任务 id=$task_id\n";
});

$serv->on('task', function ($serv, $task_id, $from_id, $data) {
echo "接收异步任务[id=$task_id]".PHP_EOL;
for ($i = 0 ; $i<10000;$i++){
if($i%2==0){
echo 'send'.$i.' success'."\n";
}else{
echo 'send'.$i.' fail'."\n";
}
sleep(1);
}

$serv->finish("$data -> OK");
});

$serv->on('finish', function ($serv, $task_id, $data) {
echo "异步任务[id=$task_id]完成".PHP_EOL;
});
$serv->start();
}
}

进入你的根目录 执行 php think websocket:start

客户端:

namespace app\index\controller;
use think\Controller;
class Test extends Controller
{
public function index(){
$client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
$ret = $client->connect("23.27.127.32", 9501);
if(empty($ret)){
echo 'error!connect to swoole_server failed';
} else {
$client->send('blue');
}
}

}

服务端显示:

thinkphp5 swoole 执行异步任务_第2张图片

你是不是多少有了解一点,但是你却对这个不精啊!免费分享tp,laravel,swoole,swoft微服务、SQL性能优化,分布式、高并发等教程,各种大牛都是1-78年PHP开发者,每天还有11年的架构师做课程讲解,助你进阶中高级PHP程序员,增值涨薪!
thinkphp5 swoole 执行异步任务_第3张图片
thinkphp5 swoole 执行异步任务_第4张图片
thinkphp5 swoole 执行异步任务_第5张图片