Swoole
https://www.swoole.com/
1.swoole是什么?
.异步、并行、高性能
.纯C编写的php扩展
2.swoole能够做什么?
.异步多线程服务器及客户端
.异步MySQL、Redis、数据库连接池、任务队列
.http/websocket服务器/客户端\
.异步文件读写
.Swoole2.0支持协程
安装:(邀请PHP7)
1.yum update
2.yum install php php-pear php-devel httpd gcc
3.pecl install swoole
4.添加php.ini扩展 php -m 查看是否成功
3.TCP服务器
//$mode -- SWOOLE_PROCESS 多进程方式(默认) //$sock_type -- SWOOLE_SOCK_TCP TCP协议(默认) $host = '0.0.0.0'; $port = 9501; $serv = new swoole_server($host,$port,SWOOLE_PROCESS,SWOOLE_SOCK_TCP); //建立连接时 $serv->on('connect',function($serv,$fd){//$serv 服务器信息 $fd客户端信息 echo "建立连接"; }); //当接收到数据时 $serv->on('receive',function($serv,$fd,$form_id,$data){ //$form_id id $data 数据 echo "接收到数据"; var_dump($data); }); //连接关闭时 $serv->on('close',function($serv,$fd){ echo "连接关闭"; }); $serv->start();
4.UDP服务器
$serv = new swoole_server('0.0.0.0',9502,SWOOLE_PROCESS,SWOOLE_SOCK_UDP); $serv->on('packet',function($serv,$data,$fd){ $serv->sendto($fd['address'],$fd['port'],"Server: $data "); var_dump($fd); }); $serv->start();
5.异步TCP服务器
$serv = new swoole_server('0.0.0.0',9501,SWOOLE_PROCESS,SWOOLE_SOCK_TCP); //设置异步进程工作数 $serv->set(array('task_worker_num'=>4)); //投递异步任务 $serv->on('receive',function($serv,$fd,$from_id,$data){ $task_id = $serv->task($data); //异步 ID echo "异步ID: $task_id"; }); //处理异步任务 $serv->on('task',function($serv,$task_id,$from_id,$data){ echo "执行异步 ID: $task_id \n"; $serv->finish($data."->OK"); }); //处理结果 $serv->on('finish',function($serv,$task_id,$fd){ echo "执行完成"; }); $serv->start();