首頁  >  文章  >  php框架  >  Think-Swoole之WebSocket 事件訂閱

Think-Swoole之WebSocket 事件訂閱

藏色散人
藏色散人轉載
2020-10-26 14:15:122342瀏覽

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

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

首先需要把之前在 app/event.php 監聽的事件給註解掉,然後建立一個監聽事件:php think make:listener SubTest 。

然後在config/swoole.php 設定中的websocket => subscribe 設定剛建立的監聽檔案:

'websocket'  => [
        .
        .
        .
        'listen'        => [],
        'subscribe'     => [
           \app\listener\SubTest::class
        ],
],

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

<?php
declare (strict_types = 1);
namespace app\listener;
class SubTest
{
    protected $websocket = null;
    public function __construct()
{
        $this -> websocket = app(&#39;\think\swoole\Websocket&#39;);
    }
    //连接事件
    public function onConnect()
{
        $this -> websocket -> emit(&#39;sendfd&#39;,$this -> websocket -> getSender());
    }
    //加入房间
    public function onJoin($event)
{
        $this -> websocket -> join($event[&#39;room&#39;]);
        $this -> websocket -> emit(&#39;joincallback&#39;,&#39;加入房间成功&#39;);
    }
    public function onRoomTest($event)
{
        $this -> websocket -> to($event[&#39;room&#39;]) -> emit(&#39;roomtestcallback&#39;,$event[&#39;message&#39;]);
    }
}

監聽事件的方法命名規格:on 事件場景識別(駝峰命名)

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

以上是Think-Swoole之WebSocket 事件訂閱的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:阿dai哥。如有侵權,請聯絡admin@php.cn刪除