ThinkPHP6.x + Swoole 使用文档整理(二)WebSocket

EN
EN
2024-02-02 / 0 评论 / 72 阅读 / 正在检测是否收录...

配置

在 config/swoole.php中,可以看到有个websocket的配置

//...
'websocket'  => [
        'enable'        => true, //开启
        'handler'       => \think\swoole\websocket\Handler::class,// \app\websocket\Manage::class ,//
        'ping_interval' => 25000,
        'ping_timeout'  => 60000,
        'room'          => [
            'type'  => 'table',
            'table' => [
                'room_rows'   => 8192,
                'room_size'   => 2048,
                'client_rows' => 4096,
                'client_size' => 2048,
            ],
            'redis' => [
                'host'          => '127.0.0.1',
                'port'          => 6379,
                'max_active'    => 3,
                'max_wait_time' => 5,
            ],
        ],
        'listen'        => [
            'Event' => \app\listener\WebsocketEvent::class,
            'message' => \app\listener\WsMessage::class,
            'Open' => \app\listener\WsConnect::class,
            'Close' => \app\listener\WsClose::class
        ],
        'subscribe'     => [
           // \app\subscribe\WsSubscribe::class
        ],
    ],
//....

handler 方法就是websocket对应的处理类

可以点进去查看一下源码。发现里面就是调用对应事件


  $this->event->trigger('swoole.websocket.Open', $request);

  $this->event->trigger('swoole.websocket.Message', $frame);

  $this->event->trigger('swoole.websocket.Event', $this->decode($frame->data));

  $this->event->trigger('swoole.websocket.Close');

配置对应的事件

创建对应的事件。

php think make:listener WebsocketEvent
...

在配置文件中,有一个listen = [ ] , 里面就是对应的事件


'Event' => \app\listener\WebsocketEvent::class,
//消息事件
'message' => \app\listener\WsMessage::class,
//客户端连接
'Open' => \app\listener\WsConnect::class,
//客户端关闭
'Close' => \app\listener\WsClose::class

WsConnect为例

<?php
declare (strict_types = 1);
namespace app\listener;
use think\swoole\Websocket;
class WsConnect
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event,Websocket $ws)
    {
        $param = request()->param(); # http请求

        echo "\n";
        echo "新用户进入\n";
        echo json_encode($param)."\n";
        echo "websocket:".$ws->getSender()."\n";
        echo "WsConnect:".json_encode($event)."\n";
        echo "\n";
       // $ws->close(); # 断开链接

    }
}

客户端

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<script>
    var ws = new WebSocket("ws://xxxxx:8080?uid=1");
    ws.onopen = function(){
        const currentTime = new Date();
        console.log(currentTime + '连接成功');
    }

    ws.onclose = function(){
        const currentTime = new Date();
        console.log(currentTime + '连接断开');
    }


</script>
</body>
</html>

有用户连接上时,控制台就会输出这些消息
lwg099yd.png

0

评论 (0)

取消