Think-Swoole之WebSocket 事件訂閱

通過前面的實例中,如果按照之前的事件監聽方式,客戶端的每個場景事件,服務端都需要創建每個對應的事件,如果事件太多, app/listener 目錄下將會有很多的文件(其實也不算什么壞現象),事件訂閱就是為了解決這一問題,把所有的事件都寫在一個文件中。

下面用事件訂閱的方式處理事件

首先需要把之前在 app/event.php 監聽的事件給注釋掉,然后創建一個監聽事件:php think make:listener SubTest 。

然后在 config/swoole.php 配置中的 websocket => subscribe 配置剛創建的監聽文件:

'websocket'??=>?[ ????????. ????????. ????????. ????????'listen'????????=>?[], ????????'subscribe'?????=>?[ ???????????applistenerSubTest::class ????????], ],

在 app/listener/SubTest.php 中定義需要監聽的事件:

<?php declare (strict_types = 1); namespace applistener; class SubTest {     protected $websocket = null;     public function __construct() {         $this ->?websocket?=?app('thinkswooleWebsocket'); ????} ????//連接事件 ????public?function?onConnect() { ????????$this?-&gt;?websocket?-&gt;?emit('sendfd',$this?-&gt;?websocket?-&gt;?getSender()); ????} ????//加入房間 ????public?function?onJoin($event) { ????????$this?-&gt;?websocket?-&gt;?join($event['room']); ????????$this?-&gt;?websocket?-&gt;?emit('joincallback','加入房間成功'); ????} ????public?function?onRoomTest($event) { ????????$this?-&gt;?websocket?-&gt;?to($event['room'])?-&gt;?emit('roomtestcallback',$event['message']); ????} }

監聽事件的方法命名規范:on+事件場景標識(駝峰命名)

用之前的前端頁面進行測試,一切正常。

? 版權聲明
THE END
喜歡就支持一下吧
點贊11 分享