EasySwoole
EasySwoole 是一款基于Swoole Server 开发的常驻内存型的分布式PHP框架,专为API而生,摆脱传统PHP运行模式在进程唤起和文件加载上带来的性能损失。 EasySwoole 高度封装了 Swoole Server 而依旧维持 Swoole Server 原有特性,支持同时混合监听HTTP、自定义TCP、UDP协议,让开发者以最低的学习成本和精力编写出多进程,可异步,高可用的应用服务
推荐(免费):swoole
安装
- 保证 PHP 版本大于等于 7.1
- 保证 Swoole 拓展版本大于等于 4.4.15
- 需要 pcntl 拓展的任意版本
- 使用 Linux / FreeBSD / MacOS 这三类操作系统
- 使用 Composer 作为依赖管理工具
composer require easyswoole/easyswoole=3.x
php vendor/easyswoole/easyswoole/bin/easyswoole install
- 新版的easyswoole安装会默认提供App命名空间,还有index控制器
- 在这里面需要填写n,不需要覆盖,已经有的
EasySwooleEvent.php
,index.php
dev.php
produce.php
- 当提示exec函数被禁用时,请自己手动执行
composer dump-autoload
命令更新命名空间
进入项目根目录执行程序,项目执行成功,访问页面
php easyswoole start
HTTP
HttpController
为控制器根目录,访问会根据url自动映射到此目录的控制器中,Index
作为默认控制器,index
为默认方法
访问http://192.168.88.16:9501
地址为默认访问到index.php
控制器中index
方法,即http://192.168.88.16:9501/index/index
地址与tp框架的访问相类似
- 我们在
index
控制器中新建一个hello
方法,打印hello world
,重新启动项目,访问http://192.168.88.16:9501/hello
和http://192.168.88.16:9501/index/hello
页面都会打印hello world
<?phpnamespace App\HttpController;use EasySwoole\Http\AbstractInterface\Controller;class Index extends Controller{ public function hello(){ $this->response()->write('hello world'); } public function index() { $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/welcome.html'; if(!is_file($file)){ $file = EASYSWOOLE_ROOT.'/src/Resource/Http/welcome.html';//欢迎页面 } $this->response()->write(file_get_contents($file)); } protected function actionNotFound(?string $action) { $this->response()->withStatus(404); $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/404.html'; if(!is_file($file)){ $file = EASYSWOOLE_ROOT.'/src/Resource/Http/404.html'; } $this->response()->write(file_get_contents($file)); }}
WebSocket
WebSocket协议在传统的phpweb框架就不适用了,在php中基本就使用workerman和swoole去解决这种场景,在easyswoole框架即是swoole的封装
- 在
dev.php
配置文件,将服务类型SERVER_TYPE
修改为EASYSWOOLE_WEB_SOCKET_SERVER
,进行WebSocket
通讯,EasySwooleEvent.php
文件中,新增主服务增加onMessage事件监听消息
<?phpnamespace EasySwoole\EasySwoole;use EasySwoole\EasySwoole\Swoole\EventRegister;use EasySwoole\EasySwoole\AbstractInterface\Event;use EasySwoole\Http\Request;use EasySwoole\Http\Response;class EasySwooleEvent implements Event{ public static function initialize() { // TODO: Implement initialize() method. date_default_timezone_set('Asia/Shanghai'); } public static function mainServerCreate(EventRegister $register) { // TODO: Implement mainServerCreate() method.\ $register->set(EventRegister::onMessage,function (\swoole_websocket_server $server, \swoole_websocket_frame $frame){ var_dump($frame); }); } public static function onRequest(Request $request, Response $response): bool { // TODO: Implement onRequest() method. return true; } public static function afterRequest(Request $request, Response $response): void { // TODO: Implement afterAction() method. }}
- 使用easyswoole的测试工具进行连接测试
WebSocket控制器
在WebSocket,一般都是在一个onmessage中写响应代码,业务复杂的情况下一个方法中非常的冗长,easyswoole提供一种类似控制器方式的写法,这里已官方的例子为例:
- 安装拓展包
composer require easyswoole/socket
dev.php
,修改SERVER_TYPE
为:
‘SERVER_TYPE’ => EASYSWOOLE_WEB_SOCKET_SERVER,
注册服务:
public static function mainServerCreate(EventRegister $register): void{ /** * **************** websocket控制器 ********************** */ // 创建一个 Dispatcher 配置 $conf = new \EasySwoole\Socket\Config(); // 设置 Dispatcher 为 WebSocket 模式 $conf->setType(\EasySwoole\Socket\Config::WEB_SOCKET); // 设置解析器对象 $conf->setParser(new WebSocketParser()); // 创建 Dispatcher 对象 并注入 config 对象 $dispatch = new Dispatcher($conf); // 给server 注册相关事件 在 WebSocket 模式下 on message 事件必须注册 并且交给 Dispatcher 对象处理 $register->set(EventRegister::onMessage, function (\swoole_websocket_server $server, \swoole_websocket_frame $frame) use ($dispatch) { $dispatch->dispatch($server, $frame->data, $frame); });}
创建App/WebSocket/WebSocketParser.php
文件
namespace App\WebSocket;use EasySwoole\Socket\AbstractInterface\ParserInterface;use EasySwoole\Socket\Client\WebSocket;use EasySwoole\Socket\Bean\Caller;use EasySwoole\Socket\Bean\Response;/** * Class WebSocketParser * * 此类是自定义的 websocket 消息解析器 * 此处使用的设计是使用 json string 作为消息格式 * 当客户端消息到达服务端时,会调用 decode 方法进行消息解析 * 会将 websocket 消息 转成具体的 Class -> Action 调用 并且将参数注入 * * @package App\WebSocket */class WebSocketParser implements ParserInterface{ /** * decode * @param string $raw 客户端原始消息 * @param WebSocket $client WebSocket Client 对象 * @return Caller Socket 调用对象 */ public function decode($raw, $client) : ? Caller { // 解析 客户端原始消息 $data = json_decode($raw, true); if (!is_array($data)) { echo "decode message error! \n"; return null; } // new 调用者对象 $caller = new Caller(); /** * 设置被调用的类 这里会将ws消息中的 class 参数解析为具体想访问的控制器 * 如果更喜欢 event 方式 可以自定义 event 和具体的类的 map 即可 * 注 目前 easyswoole 3.0.4 版本及以下 不支持直接传递 class string 可以通过这种方式 */ $class = '\\App\\WebSocket\\'. ucfirst($data['class'] ?? 'Index'); $caller->setControllerClass($class); // 提供一个事件风格的写法// $eventMap = [// 'index' => Index::class// ];// $caller->setControllerClass($eventMap[$data['class']] ?? Index::class); // 设置被调用的方法 $caller->setAction($data['action'] ?? 'index'); // 检查是否存在args if (!empty($data['content'])) { // content 无法解析为array 时 返回 content => string 格式 $args = is_array($data['content']) ? $data['content'] : ['content' => $data['content']]; } // 设置被调用的Args $caller->setArgs($args ?? []); return $caller; } /** * encode * @param Response $response Socket Response 对象 * @param WebSocket $client WebSocket Client 对象 * @return string 发送给客户端的消息 */ public function encode(Response $response, $client) : ? string { /** * 这里返回响应给客户端的信息 * 这里应当只做统一的encode操作 具体的状态等应当由 Controller处理 */ return $response->getMessage(); }}
创建App/WebSocket/Index.php文件
composer require easyswoole/task
<?php/** * Created by PhpStorm. * User: Apple * Date: 2018/11/1 0001 * Time: 14:42 */namespace App\WebSocket;use EasySwoole\EasySwoole\ServerManager;use EasySwoole\EasySwoole\Task\TaskManager;use EasySwoole\Socket\AbstractInterface\Controller;/** * Class Index * * 此类是默认的 websocket 消息解析后访问的 控制器 * * @package App\WebSocket */class Index extends Controller{ function hello() { $this->response()->setMessage('call hello with arg:'. json_encode($this->caller()->getArgs())); } public function who(){ $this->response()->setMessage('your fd is '. $this->caller()->getClient()->getFd()); } function delay() { $this->response()->setMessage('this is delay action'); $client = $this->caller()->getClient(); // 异步推送, 这里直接 use fd也是可以的 TaskManager::getInstance()->async(function () use ($client){ $server = ServerManager::getInstance()->getSwooleServer(); $i = 0; while ($i < 5) { sleep(1); $server->push($client->getFd(),'push in http at '. date('H:i:s')); $i++; } }); }}
- 用
websocket
测试工具进行测试,进行提交的json
自动到相应的控制器方法中进行处理
以上是介绍EasySwoole安装使用的详细内容。更多信息请关注PHP中文网其他相关文章!

本文概述了为Swoole项目做出贡献的方法,包括报告错误,提交功能,编码和改进文档。它讨论了初学者开始贡献的必要技能和步骤,以及如何找到紧迫的是

本文讨论了在PHP中使用Swoole的异步I/O功能用于高性能应用程序。它涵盖安装,服务器设置和优化策略。单词计数:159

Swoole的反应堆模型使用事件驱动的,非阻滞I/O架构来有效地管理高持续性场景,通过各种技术优化性能。(159个字符)(159个字符)

摘要:本文讨论了通过识别,隔离和固定解决SWOORE应用程序中的内存泄漏,并强调了常见原因,例如不当资源管理和不受管理的Coroutines。 Swoole Tracker和Valgrind等工具


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

Atom编辑器mac版下载
最流行的的开源编辑器

Dreamweaver CS6
视觉化网页开发工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能