1

我正在创建一个多线程服务器,我一直在解决这个问题。要接受和处理连接,我使用 socket_accept,然后创建一个 Connection 对象,将其添加到数组中,然后通过所有数组获取。但是由于某种原因,当我在执行 $connection::read (执行 socket_read)时,此对象中的套接字变为 0。但是当构造对象时,一切都很好,转储套接字返回资源,但在读取时转储相同的套接字() 抛出警告,因为套接字为 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);
    }


4

0 回答 0