为什么对象中的套接字设置为0

时间:2019-02-05 18:59:59

标签: php multithreading php-pthread

我正在创建多线程服务器,但我一直坚持这个问题。要接受和处理连接,我正在使用socket_accept,然后创建一个Connection对象,将其添加到数组中,然后获取所有数组。但是由于某种原因,当我正在执行$ connection :: read(它执行socket_read)时,该对象中的套接字变为0。但是当构造对象时,一切都很好,转储套接字返回资源,但转储相同的套接字为read ()发出警告,因为套接字为0。这里有一些代码

ThreadedServer, run()
        while ($this->enabled){
            foreach ($this->connections as $connection){
                /** @var $connection Connection */
                $msg = $connection->read(); //here it's already 0, and i'm getting many warnings
                if($msg){
                    //todo
                }
            }
            if (($clientSocket = socket_accept($this->socket))) {
                socket_getpeername($clientSocket, $addr, $port);
                $this->connections[$hash = self::hash($addr, $port)] = new Connection($clientSocket, $addr, $port, $this);
                $this->logger->info("New connection accepted: $hash");
            }
        }
Connection, in same thread with the ThreadedServer
    public function __construct($socket, string $address, int $port, ThreadedServer $server)
    {
        $this->socket = $socket;
        //socket_set_nonblock($this->socket); //not needed?
        var_dump($this->socket); //here it returns 'resource'
        $this->server = $server;
        $this->lastUpdate = microtime(true);
        $this->address = $address;
        $this->port = $port;
    }

    public function read(){
        var_dump($this->socket); //here it returns 'int (0)'
        return socket_read($this->socket, 1024);
    }


0 个答案:

没有答案