为什么$ handler在回调中获得不同的值?

时间:2016-02-22 17:33:37

标签: php websocket rabbitmq

每当我在回调中打印处理程序的客户端时,即使添加了少量客户端,它也会显示为空。

我对PHP很天真似乎每当我调用回调函数时,处理程序的新对象都会被传递。

{
    <?php

    $handler=new Handler();

    $server = IoServer::factory(
       new HttpServer(
           new WsServer(
            $handler
           )
       ),
       9090   
    );
    $callback = function($msg) {
    echo " [x] Received ", $msg->body, "\n";
    echo $handler->test."\n";
    };
    $pid=pcntl_fork(); 
    if ( $pid == -1 ) {       
        echo "server start fork failed";
        exit(1);
    } else if ( $pid ) {
        $server->run();
    } 


    $connection = new AMQPStreamConnection('localhost', 5672, 'guest',     'guest');
    $channel = $connection->channel();
    $channel->queue_declare('hello', false, false, false, false);
    $channel->basic_consume('hello', '', false, true, false, false, $callback);
    while(count($channel->callbacks)) {
       $channel->wait();
    echo count($channel->callbacks);
    }

    ?>
}

以下是处理程序文件

{
    <?php
    namespace MyApp;
    use Ratchet\MessageComponentInterface;
    use Ratchet\ConnectionInterface;
    class Handler implements MessageComponentInterface {

    public $clients;  
    public $test="Test";

    private $handler;
    public function __construct() 
    {    
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) 
    {
        "echo  added";
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) 
    {            
        $this->test="onMessage";

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
    }
    public function sendAll($msg) 
    {            

        $this->test="sendAll";
        foreach ($this->clients as $client) {
            $client->send($msg);        
        }
    }

    public function onClose(ConnectionInterface $conn) 
    {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) 
    {     
        $conn->close();
    }
    public function getInstance(){
        if(empty($this->handler))
        {
            $this->handler=new Handler();
        }
        return $this->handler;
    }

    } 

    ?>
}

1 个答案:

答案 0 :(得分:0)

使用单身人士。

不是这个:

// class Handler... 
private $handler;
...
public function getInstance(){
    if(empty($this->handler))
    {
        $this->handler=new Handler();
    }
    return $this->handler;
}

$handler=new Handler();

但是这个:

// Changed class Handler... 
private static $handler;
...
public static function getInstance(){
    if(empty(self::$handler))
    {
        self::$handler=new Handler();
    }
    return self::$handler;
}

$handler=Handler::getInstance();

[edit] Handler :: getInstance()目前不是静态的,在我写完答案后就抓住了。