1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
| composer require topthink/think-swoole ```
```bash php think swoole [start|stop|reload|restart] ```
当你在命令行`php think swoole`下执行完成之后就会启动一个HTTP Server,可以直接访问当前的应用
~~~bash 'server' => [ 'host' => env('SWOOLE_HOST', '0.0.0.0'), // 监听地址 'port' => env('SWOOLE_PORT', 9501), // 监听端口 'mode' => SWOOLE_PROCESS, // 运行模式 默认为SWOOLE_PROCESS 'sock_type' => SWOOLE_SOCK_TCP, // sock type 默认为SWOOLE_SOCK_TCP 'options' => [ // 服务启动后,进程ID存放文件 'pid_file' => runtime_path() . 'swoole.pid', // swoole 的日志文件 'log_file' => runtime_path() . 'swoole.log', // 守护进程模式设置 true 后台运行 'daemonize' => false, // 设置启动的reactor线程数 'reactor_num' => swoole_cpu_num(), // 设置启动的worker进程数 'worker_num' => swoole_cpu_num(), //配置Task进程的数量 'task_worker_num' => swoole_cpu_num(), //开启静态文件请求处理,需配合document_root 'enable_static_handler' => true, //静态文件根目录 'document_root' => root_path('public'), // 设置最大数据包尺寸,单位字节 'package_max_length' => 20 * 1024 * 1024, //配置发送输出缓冲区内存尺寸 'buffer_output_size' => 10 * 1024 * 1024, //设置客户端连接最大允许占用的内存数量 'socket_buffer_size' => 128 * 1024 * 1024, ], ], ```
swoole服务器运行过程中php文件是常驻内存运行,这样就可以避免重复的读取磁盘,重复的解释编译php,以便达到最高的性能,所以修改代码需要重启服务
think-swoole扩展提供热更新功能,在检测相关文件有更新会自动重启,不在需要手动完成重启,方便开发调试
生产环境下不建议开始文件监控,性能损耗,正常情况下你所修改的文件需要确认无误才能进行更新部署
`.env`里面设置`APP_DEBUG = true`会默认开启热更新
~~~bash 'hot_update' => [ 'enable' => env('APP_DEBUG', false), 'name' => ['*.php'], 'include' => [app_path()], 'exclude' => [], ], ```
参数说明
| 参数 | 说明 | | ------- | ------------------------ | | enable | 是否开启热更新 | | name | 监听哪些类型的文件变动 | | include | 监听哪些目录下的文件变动 | | exclude | 排除目录 |
先来一个官方的例子
~~~bash $server = new Swoole\WebSocket\Server("0.0.0.0", 9501); $server->on('open', function (Swoole\WebSocket\Server $server, $request) { echo "server: handshake success with fd{$request->fd}\n"; }); $server->on('message', function (Swoole\WebSocket\Server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data}\n"; $server->push($frame->fd, "this is server"); }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start(); ```
开启think-swoole的websocket功能 `\config\swoole.php`
~~~bash 'websocket' => [ 'enable' => true, ], ```
创建三个事件
~~~bash php think make:listener SwWsConnect php think make:listener SwWsClose php think make:listener SwWsMessage ```
然后将这三个事件写到到事件监听中,分别有以下2中文件可以修改方式,注意二选一
thinkphp6自带的事件绑定`app\event.php`
~~~bash 'listen' => [ ........ // 监听链接 'swoole.websocket.Connect' => [ \app\listener\SwWsConnect::class ], //关闭连接 'swoole.websocket.Close' => [ \app\listener\SwWsClose::class ], //发送消息场景 'swoole.websocket.Message' => [ \app\listener\SwWsMessage::class ] ], ```
think-swoole事件绑定`config\swoole.php`
~~~bash 'listen' => [ 'connect'=>\app\listener\SwWsConnect::class, 'close'=>\app\listener\SwWsClose::class, 'message'=> \app\listener\SwWsMessage::class ], ```
> 怎么选择是保存在`config\swoole.php`还是`app\event.php`配置中呢? > > 首先我们 我们确定一下我们这个项目中存在有几个实时通讯, > > 如果只是存在一个实时通讯 个人建议 保存在`config\swoole.php` > > 如果是存在多个实时通讯,就保存在`app\event.php` > > key值 必须是`swoole.websocket.事件名称` 例如 `swoole.websocket.Message`
开始写事件中中方法
连接事件`app\listener\SwWsConnect.php`
~~~bash public function handle($event, \think\swoole\websocket $ws) { // 获取当前发送者的fd $fd = $ws->getSender(); echo "server: handshake success with fd{$fd}\n"; } ```
关闭事件`app\listener\SwWsClose.php`
~~~bash
public function handle($event, \think\swoole\websocket $ws) { $fd = $ws->getSender(); echo "client {$fd} closed\n"; } ```
message事件`app\listener\SwWsMessage.php`
~~~bash public function handle($event, \think\swoole\websocket $ws) { $fd = $ws->getSender(); $data = json_encode($event); echo "receive from {$fd}:{$data}\n"; $ws->emit("this is server", $fd); } ```
启动`php think swoole`进行测试
think-swoole中的websocket方法总结
~~~bash //给自己发消息 $ws->emit("this is server", $ws->getSender()); //给指定一个fd发消息 $ws->to($to)->emit("messagecallback",$data); //给指定多个人发消息 $ws->to([1,2,3])->emit("messagecallback",$data); //发送给所有的(不包含自己) $ws->broadcast()->emit("messagecallback",$data); //模拟formfd 给tofd 发送消息 $ws->setSender($formfd)->to($tofd)->emit("messagecallback",$data); ```
> 注意:在多个实时通讯场景下使用 `emit` > > 第一个参数传入 传入 事件名称callback 例如 `messagecallback`
如果你发现你think-swoole中有些没有swoole中的方法可以这么干
~~~bash $sw = app('swoole.server'); $sw = app("think\swoole\Manager")->getServer(); //以上二选一
$es = $sw->isEstablished($fd); //检查连接是否为有效的WebSocket客户端连接 var_dump($es); ```
前端文件参考 `html\room.html` 或 `html\room-socket-io.html`
~~~bash php think make:listener SwRoomJoin php think make:listener SwRoomLeave php think make:listener SwRoomMessage ```
事件绑定
~~~bash // 加入房间 'swoole.websocket.RoomJoin' => [ \app\listener\SwRoomJoin::class ], // 离开房间 'swoole.websocket.Roomleave' => [ \app\listener\SwRoomLeave::class ], // 在房间发消息 'swoole.websocket.RoomMessage' => [ \app\listener\SwRoomMessage::class ] ```
加入房间逻辑
~~~bash public function handle($event, \think\swoole\websocket $ws, \think\swoole\websocket\room $room) { $fd = $ws->getSender(); //客户端假如定的room $roomid = $event['room']; //获取指定房间下有哪些客户端 $roomfds = $room->getClients($roomid); // 判断这个房间有没有自己 如果有自己就不需要再次发送通知 if (in_array($fd, $roomfds)) { $ws->to($roomfds)->emit("roomjoincallback", "房间{$roomid}已加入"); return; } //加入房间 $ws->join($roomid); $ws->to($roomfds)->emit("roomjoincallback", "{$fd}加入房间{$roomid}成功"); } ```
离开房间逻辑
~~~bash public function handle($event, \think\swoole\websocket $ws, \think\swoole\websocket\Room $room) { $roomid = $event['room']; $fd = $ws->getSender(); $roomfds = $room->getClients($roomid); if (!in_array($fd, $roomfds)) { $ws->emit("roomleavecallback", "{$fd}不在{$roomid}房间内,怎么离开~"); return; } //离开房间 $ws->leave($roomid); //获取当前客户端加入了哪些客户端 $rooms = $room->getRooms($fd); $ws->to($roomfds)->emit("roomleavecallback", "{$fd}已离开了~~"); } ```
在房间发布聊天逻辑
~~~bash public function handle($event, \think\swoole\websocket $ws, \think\swoole\websocket\room $room) { // $roomid = $event['room']; $text = $event['text']; $fd = $ws->getSender(); $roomfds = $room->getClients($roomid); if (!in_array($fd, $roomfds)) { $ws->emit("roommessagecallback", "{$fd}不在{$roomid}房间内,无法进入发布聊天~"); return; } $ws->to($roomfds)->emit("roommessagecallback", $text); } ```
~~~bash php think make:listener SwSubscribe ```
app\listener\SwSubscribe.php
~~~bash <?php declare (strict_types = 1);
namespace app\listener;
class SwSubscribe { protected $ws = null;
// public function __construct() // { // $this->ws = app('think\swoole\Websocket'); // }
public function __construct(\think\Container $c) { $this->ws = $c->make(\think\swoole\Websocket::class); } public function onConnect() { $fd = $this->ws->getSender(); echo "server: handshake success with fd{$fd}\n"; } public function onClose() { $fd = $this->ws->getSender(); echo "client {$fd} closed\n"; } public function onMessage($event) { $fd = $this->ws->getSender(); var_dump($event); echo "server: handshake success with fd{$fd}\n"; $this->ws->emit("this is server", $fd); } }
```
> 有点类似 将原生的swoole代码改成面向对象代码,生效方法 `config\swoole.php`中在`subscribe` 加入`\app\listener\SwSubscribe::class` > > ~~~bash > 'subscribe' => [ > \app\listener\SwSubscribe::class > ],
|