EasySwoole WebSocket

添加文件

  • App/WebSocket/Index.php
  • App/WebSocket/WebSocketEvent.php
  • App/WebSocket/WebSocketParser.php
  • EasySwooleEvent.php

修改文件

  • EasySwooleEvent.php

Index.php

<?php
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
{
    public 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());
    }

    public function index()
    {
        //$this->response()->setMessage('你的fd是:'. $this->caller()->getClient()->getFd());

        //print_r($this->caller());

        //echo PHP_EOL;

        //print_r($this->caller()->getArgs());

        print_r($this->caller()->getArgs()); //获取参数

        echo PHP_EOL;

        //print_r(ServerManager::getInstance()->getSwooleServer());
    }

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

    /*
     * HTTP 触发向某个客户端单独推送消息
     * @example http://ip:9501/WebSocketTest/push?fd=2
     */
    public function push()
    {
        $fd = $this->request()->getRequestParam('fd');

        if (is_numeric($fd)) {
            /** @var \swoole_websocket_server $server */
            $server = ServerManager::getInstance()->getSwooleServer();
            $info = $server->getClientInfo($fd);

            if ($info && $info['websocket_status'] === WEBSOCKET_STATUS_FRAME) {
                $server->push($fd, 'http push to fd '.$fd.' at '.date('H:i:s'));
            } else {
                $this->response()->write("fd {$fd} is not exist or closed");
            }
        } else {
            $this->response()->write("fd {$fd} is invalid");
        }
    }

    /**
     * 使用 HTTP 触发广播给所有的 WS 客户端
     *
     * @example http://ip:9501/WebSocketTest/broadcast
     */
    public function broadcast()
    {
        /** @var \swoole_websocket_server $server */
        $server = ServerManager::getInstance()->getSwooleServer();
        $start = 0;

        // 此处直接遍历所有 FD 进行消息投递
        // 生产环境请自行使用 Redis 记录当前在线的 WebSocket 客户端 FD
        while (true) {
            $conn_list = $server->connection_list($start, 10);

            if (empty($conn_list)) {
                break;
            }

            $start = end($conn_list);

            foreach ($conn_list as $fd) {
                $info = $server->getClientInfo($fd);

                /** 判断此fd 是否是一个有效的 websocket 连接 */
                if ($info && $info['websocket_status'] == WEBSOCKET_STATUS_FRAME) {
                    $server->push($fd, 'http broadcast fd '.$fd.' at '.date('H:i:s'));
                }
            }
        }
    }
}

WebSocketEvent.php

<?php
namespace App\WebSocket;

use swoole_http_request;
use swoole_http_response;

/**
 * Class WebSocketEvent
 *
 * 此类是 WebSocet 中一些非强制的自定义事件处理
 *
 * @package App\WebSocket
 */
class WebSocketEvent
{
    /**
     * 握手事件
     *
     * @param  swoole_http_request  $request
     * @param  swoole_http_response  $response
     * @return bool
     */
    public function onHandShake(swoole_http_request $request, swoole_http_response $response)
    {
        /** 此处自定义握手规则 返回 false 时中止握手 */
        if (!$this->customHandShake($request, $response)) {
            $response->end();

            return false;
        }
        /** 此处是  RFC规范中的WebSocket握手验证过程 必须执行 否则无法正确握手 */
        if ($this->secWebsocketAccept($request, $response)) {
            $response->end();

            return true;
        }
        $response->end();

        return false;
    }

    /**
     * 自定义握手事件
     *
     * @param  swoole_http_request  $request
     * @param  swoole_http_response  $response
     * @return bool
     */
    protected function customHandShake(swoole_http_request $request, swoole_http_response $response): bool
    {
        /**
         * 这里可以通过 http request 获取到相应的数据
         * 进行自定义验证后即可
         * (注) 浏览器中 JavaScript 并不支持自定义握手请求头 只能选择别的方式 如get参数
         */
        $headers = $request->header;
        $cookie = $request->cookie;
        // if (如果不满足我某些自定义的需求条件,返回false,握手失败) {
        //    return false;
        // }
        return true;
    }

    /**
     * 关闭事件
     *
     * @param  \swoole_server  $server
     * @param  int  $fd
     * @param  int  $reactorId
     */
    public function onClose(\swoole_server $server, int $fd, int $reactorId)
    {
        /** @var array $info */
        $info = $server->getClientInfo($fd);

        print_r($info);

        /**
         * 判断此fd 是否是一个有效的 websocket 连接
         * 参见 https://wiki.swoole.com/wiki/page/490.html
         */
        if ($info && $info['websocket_status'] === WEBSOCKET_STATUS_FRAME) {
            /**
             * 判断连接是否是 server 主动关闭
             * 参见 https://wiki.swoole.com/wiki/page/p-event/onClose.html
             */
            if ($reactorId < 0) {
                echo "server close \n";
            }
        }
    }

    /**
     * RFC规范中的WebSocket握手验证过程
     * 以下内容必须强制使用
     *
     * @param  swoole_http_request  $request
     * @param  swoole_http_response  $response
     * @return bool
     */
    protected function secWebsocketAccept(swoole_http_request $request, swoole_http_response $response): bool
    {
        // ws rfc 规范中约定的验证过程
        if (!isset($request->header['sec-websocket-key'])) {
            // 需要 Sec-WebSocket-Key 如果没有拒绝握手
            var_dump('shake fai1 3');

            return false;
        }

        if (0 === preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $request->header['sec-websocket-key'])
            || 16 !== strlen(base64_decode($request->header['sec-websocket-key']))
        ) {
            //不接受握手
            //var_dump('shake fai1 4');
            return false;
        }

        $key = base64_encode(sha1($request->header['sec-websocket-key'].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));

        $headers = array(
            'Upgrade' => 'websocket',
            'Connection' => 'Upgrade',
            'Sec-WebSocket-Accept' => $key,
            'Sec-WebSocket-Version' => '13',
            'KeepAlive' => 'off',
        );

        if (isset($request->header['sec-websocket-protocol'])) {
            $headers['Sec-WebSocket-Protocol'] = $request->header['sec-websocket-protocol'];
        }

        // 发送验证后的header
        foreach ($headers as $key => $val) {
            $response->header($key, $val);
        }

        // 接受握手 还需要101状态码以切换状态
        $response->status(101);

        //var_dump('shake success at fd :' . $request->fd);

        return true;
    }
}

WebSocketParser.php

<?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|null         Socket  调用对象
     */
    public function decode($raw, $client): ?Caller
    {
        // 解析 客户端原始消息
        try {
            $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        } catch (\JsonException $e) {
            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);

        // 设置被调用的方法
        $caller->setAction($data['action'] ?? 'index');

        // 检查是否存在 args
        if (!empty($data['params'])) {
            // params无法解析为 array 时,返回 params => string 格式
            $args = is_array($data['params']) ? $data['params'] : ['params' => $data['params']];
        }

        // 设置被调用的 args
        $caller->setArgs($args ?? []);

        return $caller;
    }

    /**
     * encode
     * @param  Response  $response  Socket    Response 对象
     * @param  WebSocket  $client  WebSocket Client   对象
     * @return string|null 发送给客户端的消息
     */
    public function encode(Response $response, $client): ?string
    {
        /**
         * 这里返回响应给客户端的信息
         * 这里应当只做统一的 encode 操作 具体的状态等应当由 Controller 处理
         */
        return $response->getMessage();
    }
}

EasySwooleEvent.php

<?php
namespace EasySwoole\EasySwoole;

use App\WebSocket\WebSocketParser;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\Socket\Dispatcher;
use App\WebSocket\WebSocketEvent;

class EasySwooleEvent implements Event
{
    public static function initialize()
    {
        date_default_timezone_set('Asia/Shanghai');
    }

    public static function mainServerCreate(EventRegister $register): void
    {
        // 创建一个 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 模式下,onMessage 事件必须注册,并且交给 Dispatcher 对象处理
        $register->set(EventRegister::onMessage,
            function (\swoole_websocket_server $server, \swoole_websocket_frame $frame) use ($dispatch) {

                $dispatch->dispatch($server, $frame->data, $frame);

            });

        // 自定义握手事件
        $websocketEvent = new WebSocketEvent();

        // 自定义关闭事件
        $register->set(EventRegister::onClose,
            function (\swoole_server $server, int $fd, int $reactorId) use ($websocketEvent) {
                $websocketEvent->onClose($server, $fd, $reactorId);
            });
    }

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

验证

www.easyswoole.com/wstool.html

请求 Body:

{"class":"Index","action":"index","params":{"name":"hello"}}

来源

www.css3er.com/p/251.html

本作品采用《CC 协议》,转载必须注明作者和本文链接
无论在现实或是网络中,我都是孤独的。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!