1. 程式人生 > >swoole websocket 會話間上下文變數儲存隔離情況測試

swoole websocket 會話間上下文變數儲存隔離情況測試

先貼一下大致程式碼:

class wsServer
{
    private $serv;
    private $userS;

    public function __construct()
    {
    	#========================start 前將serv變成類成員變數=======================
        $this->serv = new swoole_websocket_server("0.0.0.0", 9501);

        $this->serv->set(array(
            'worker_num' => 4,
            'daemonize' => false,
        ));

        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Open', array($this, 'onOpen'));
        $this->serv->on('Message', array($this, 'onMessage'));
        $this->serv->on('Close', array($this, 'onClose'));
        $this->serv->start();
    }
    public function onStart(swoole_server $server)
    {
        $msec = 2000;
        swoole_timer_tick($msec, array($this,'bubbleTask'));
    }

    public function onOpen(swoole_websocket_server $server, swoole_http_request $request)
    {
        swoole_timer_tick(5000,function() use ($server,$request){
            if (!$server->exist($request->fd)){
                return $this->closeFd($server,$request->fd);
            };
        });
        echo "server: handshake success with fd{$request->fd}\n";
    }
    public function onMessage(swoole_websocket_server  $server, swoole_websocket_frame $frame)
    {
        $fd = $frame->fd;
        if ($frame->data === 'look'){
            foreach ($this->serv->connections as $fd){
                echo $fd.PHP_EOL;
            }
            echo 'uid:'.UserService::uid().PHP_EOL;
            var_dump($this->userS);
            var_dump($this->userS->tUid());

            return $this->alive($server,$fd);
        }

        $data = json_decode($frame->data,1);
        if ($data === false){
           return $server->push($fd,json_encode(['code'=>5001,'msg'=>'格式錯誤']));
        }

        $uid = $this->checkLogin($server,$fd,$data);
        if (!is_numeric($uid)){
            return false;
        }
        echo '------------';
        var_dump($uid);
        echo PHP_EOL.$fd;
        echo '============';

    }

    private function checkLogin($server,$fd,$data) : ?int
    {
        //login
        $uid = null;
        if (empty($uid) && !isset($data['token'])){
            $server->push($fd,json_encode(['code'=>5002,'msg'=>'請登陸'],JSON_UNESCAPED_UNICODE));
        }
        if (empty($uid) && !empty($data['token']) && is_string($data['token'])){
            #=======回話過程中測試靜態變數以及類常量是否被隔離===========
            $userS = new UserService();
            $this->userS = $userS;
            $uid = $userS->getUid($data['token']);
        }
        if (is_null($uid)){
            $server->push($fd,json_encode(['code'=>5003,'msg'=>'請登陸,token不正確'],JSON_UNESCAPED_UNICODE));
        }
        return $uid;
    }

    public function onClose(swoole_websocket_server $server, $fd, $from_id ) :void
    {
        echo "Client {$fd}-{$from_id}: close connection\n";
    }
   
<?php
/**
 * Created by PhpStorm.
 * User: 彭帥飛
 * Date: 2018/9/27
 * Time: 13:33
 */
namespace lib;

class UserService
{
    public static $uid = null;
    public $tUid = null;

    public function getUid($token) : ?int
    {
        $uid = null;
        $db = new \Swoole\Coroutine\MySQL();
        $dbConfig = getDbConfig('xd');
        $db ->connect($dbConfig);
        $sql = "select * from weili_api_userlogin where user_token = '{$token}'";
        $r = $db->query($sql);
        if (!empty($r) && is_array($r)){
            $row = array_shift($r);
            if (is_array($row) && isset($row['user_id'])){
                $uid = $row['user_id'];
            }
        }
        self::$uid = $uid;
        $this->tUid = $uid;
        return $uid;
    }

     public static function uid()
    {
        return self::$uid;
    }
    public function tUid()
    {
        return $this->tUid;
    }

}

會話1呼叫登陸(賦值類常量,賦值類成員變數),其他均不呼叫 結果: 會話1結果: 會話上下文變數儲存正常 正常 會話2、3: 會話間隔離狀況正常不會找到其他會話

正常