• 技术文章 >php框架 >Swoole

    介绍EasySwoole安装使用

    coldplay.xixicoldplay.xixi2021-03-19 11:21:29转载876

    EasySwoole

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

    推荐(免费):swoole

    安装

    composer require easyswoole/easyswoole=3.x
    php vendor/easyswoole/easyswoole/bin/easyswoole install

    进入项目根目录执行程序,项目执行成功,访问页面

    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框架的访问相类似

    <?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的封装

    <?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.
        }}

    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++;
                }
            });
        }}

    以上就是介绍EasySwoole安装使用的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:CSDN,如有侵犯,请联系admin@php.cn删除
    专题推荐:EasySwoole安装使用
    上一篇:swoole学习之异步Mysql 下一篇:介绍swoole异步群发模板消息
    大前端线上培训班

    相关文章推荐

    • easyswoole 启动TableManager+Cache工具的原理• EasySwoole 基础入门• 带你学习swoole_process• Swoole与HTTP• 分享Swoole引擎原理的快速入门干货• PHP创始人​​​​​​​和Swoole创始人投反对票,协程提案Fiber引激辩

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网