EN博客 - 归来仍是菜鸟 - WebSocket
type: channel
link: https://0en.cn/tag/WebSocket/
items: ThinkPHP6.x + Swoole 使用文档整理（二）WebSocket

ThinkPHP6.x + Swoole 使用文档整理（二）WebSocket
type: item
date: 2024-02-02T14:11:00+08:00
description: 配置在 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::classWsConnect为例<?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(); # 断开链接 } } 客户端 Document 有用户连接上时，控制台就会输出这些消息