swoole 2人聊天 demo

<?php
class Ws
{
    protected $host = "0.0.0.0";
    protected $port = 8812;
    public $ws = null;

    public function __construct()
    {
        $this->ws = new Swoole\WebSocket\Server($this->host, $this->port);

        $this->ws->set(
            [
                'worker_num' => 2,
                'task_worker_num' => 2,
            ]
        );
        $this->ws->on("open", [$this, 'onOpen']);
        $this->ws->on("message", [$this, 'onMessage']);
        $this->ws->on("task", [$this, 'onTask']);
        $this->ws->on("finish", [$this, 'onFinish']);
        $this->ws->on("close", [$this, 'onClose']);
        $this->ws->start();
    }

    /**
     * 監聽ws連接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request)
    {
        var_dump($request->fd);
        var_dump($request);
        /* if ($request->fd == 1) {
            //每2秒執行
             swoole_timer_tick(2000, function ($timer_id) {
                 echo "2s: timerId:{$timer_id}\n";
             });
        }*/
    }

    /**
     * 監聽ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame)
    {
        echo "ser-push-message:{$frame->data}\n";
        $after_data = json_decode($frame->data, true);
        //用戶登錄時鏈接該socket時,進行存儲用戶的$frame->fd
        if (isset($after_data['user_id'])) {
            (new iRedis())->setUserFd($after_data['user_id'], $frame->fd);
        }
        //執行給單個用戶發送信息的邏輯
        if (isset($after_data['uid'])) {
            //根據獲得的uid進行查詢數據庫得到該用戶的$frame->fd,並判斷用戶是否在線,在線時進行發送信息
            $user_status = (new iRedis())->getUserIdStatus($after_data['uid']);
            if ($user_status) {
                $user_fd = (new iRedis())->getUserFd($after_data['uid']);
                $ws->push($user_fd, json_encode($frame->data));
            }else{
                //進行存儲消息,待用戶上線的時候發送消息
            }
        }
        //echo $frame->fd . PHP_EOL;
        // todo 10s
        /*$data = [
           'task' => 1,
           'fd' => $frame->fd,
       ];
       $ws->task($data);
       /*
    swoole_timer_after(5000, function () use ($ws, $frame) {
           echo "5s-after\n";
           $ws->push($frame->fd, "server-time-after:");
       });*/

    }

    /**
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     */
    public function onTask($serv, $taskId, $workerId, $data)
    {
        //print_r($data);
        // 耗時場景 10s
        //sleep(10);
        return "on task finish"; // 告訴worker
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $data
     */
    public function onFinish($serv, $taskId, $data)
    {
        echo "taskId:{$taskId}\n";
        echo "finish-data-sucess:{$data}\n";
    }

    /**
     * close
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd)
    {
        echo "clientid:{$fd}\n";
    }
}
class iRedis
{
    protected $host = "127.0.0.1";
    protected $port = 6379;
    public $redis = null;

    public function __construct()
    {
        $this->redis = new Redis();
        $this->redis->connect($this->host, $this->port);
    }

    public  function setUserFd($userId, $fd)
    {
        $this->redis->set($userId, $fd);
        $this->redis->set($userId . '_status', 1);
    }

    public  function getUserFd($userId)
    {
        return  $this->redis->get($userId);
    }

    public function getUserIdStatus($userId)
    {
        return   $this->redis->get($userId . '_status');
    }

    public function closeUserFd($userId)
    {
        return   $this->redis->set($userId . '_status', 0);
    }
}
$obj = new Ws();

js代碼

<script>
    var websocket = new WebSocket("ws://111.231.74.213:8812");

    //實例對象的onopen屬性
    websocket.onopen = function (evt) {
        console.log('首次鏈接的時候,發送改的uid')
        websocket.send('{"user_id":1}');
    }

    // 實例化 onmessage
    websocket.onmessage = function (evt) {
        console.log("ws-server-return-data:" + evt.data);
    }

    //onclose
    websocket.onclose = function (evt) {
        console.log("close");
    }
    //onerror

    websocket.onerror = function (evt, e) {
        console.log("error:" + evt.data);
    }
	
    function sendmessage() {
    //uid 發送給需要接收的用戶
        websocket.send('{"uid":"2","message":"' + document.getElementById('input').value + '"}');
    }

</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章