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 push($client->getFd(),'push in http at '. date('H:i:s')); $i++; } }); }}
- 用
websocket
测试工具进行测试,进行提交的json
自动到相应的控制器方法中进行处理
The above is the detailed content of Introduction to the installation and use of EasySwoole. For more information, please follow other related articles on the PHP Chinese website!

This tutorial details Swoole installation methods (PECL, manual, Docker), addressing common OS and user scenarios. It covers troubleshooting, including dependency issues and configuration problems, and offers best practices for post-installation opt

This article provides a comprehensive guide to compiling and installing the Swoole PHP extension. It details prerequisites, step-by-step instructions, common pitfalls (missing dependencies, incorrect paths, permissions), and optimization strategies

This tutorial introduces Swoole, a high-performance asynchronous PHP networking engine. It details Swoole server setup, highlighting crucial aspects like asynchronous operations, memory management, and efficient worker process utilization to avoid c

This guide details Swoole installation on Linux, using Composer (recommended) or PECL. It addresses prerequisites (PHP, Composer/PECL, development packages), common installation issues (missing dependencies, PHP version mismatches), and alternative

The article discusses using Swoole's memory pool to reduce memory fragmentation by efficient memory management and configuration. Main focus is on enabling, sizing, and reusing memory within the pool.

Article discusses extending Swoole with custom modules, detailing steps, best practices, and troubleshooting. Main focus is enhancing functionality and integration.

This article explores popular Swoole PHP frameworks, highlighting Hyperf, EasySwoole, and Swoft. Key differences discussed include feature complexity, learning curve, community support, and performance. The article emphasizes that framework selecti

This article guides users on leveraging Swoole, an asynchronous PHP framework, for enhanced performance and real-time capabilities. It addresses the challenges of learning Swoole, suggesting resources like official documentation, YouTube tutorials,


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
