EasySwoole安装使用

EasySwoole

EasySwoole 是一款基于Swoole Server 开发的常驻内存型的分布式PHP框架,专为API而生,摆脱传统PHP运行模式在进程唤起和文件加载上带来的性能损失。 EasySwoole 高度封装了 Swoole Server 而依旧维持 Swoole Server 原有特性,支持同时混合监听HTTP、自定义TCP、UDP协议,让开发者以最低的学习成本和精力编写出多进程,可异步,高可用的应用服务

安装

  • 保证 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.phpindex.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/hellohttp://192.168.88.16:9501/index/hello页面都会打印hello world
<?php


namespace 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事件监听消息
<?php
namespace 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.
    }
}

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是一个基于Swoole扩展的PHP框架,它提供了一种简单且高效的方式来构建WebSocket应用程序。WebSocket是一种在Web浏览器和服务器之间进行全双工通信的协议,它允许服务器主动向客户端推送数据,而不需要客户端发起请求。 使用easyswoole可以轻松地创建和管理WebSocket服务器,并处理来自客户端的连接、消息和事件。下面是一个简单的示例代码,演示了如何使用easyswoole创建一个WebSocket服务器: ```php <?php use EasySwoole\EasySwoole\ServerManager; use EasySwoole\EasySwoole\Swoole\EventRegister; use EasySwoole\EasySwoole\AbstractInterface\Event; use Swoole\WebSocket\Frame; use Swoole\WebSocket\Server; // 注册WebSocket事件回调 Event::getInstance()->set(EventRegister::onMessage, function (Server $server, Frame $frame) { // 处理收到的消息 $data = $frame->data; // TODO: 处理消息逻辑 // 向客户端发送消息 $server->push($frame->fd, 'Hello, client!'); }); // 创建WebSocket服务器 $server = ServerManager::getInstance()->getSwooleServer(); $server->on('WorkerStart', function () { echo "WebSocket server started\n"; }); // 启动服务器 EasySwoole\EasySwoole\Core::getInstance()->initialize(); ``` 上述代码中,我们首先注册了一个`onMessage`事件回调函数,用于处理收到的消息。在这个示例中,我们简单地向客户端发送了一条回复消息。然后,我们创建了一个WebSocket服务器,并在`WorkerStart`事件回调中输出了一条启动消息。最后,我们使用`EasySwoole\EasySwoole\Core::getInstance()->initialize()`启动了服务器。 请注意,上述代码只是一个简单的示例,实际应用中可能需要更复杂的逻辑来处理不同的消息和事件。你可以根据自己的需求进行扩展和定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值