Why socket in object sets to 0

55 Views Asked by At

I'm creating a multithreaded server, and i've stucked on this problem. To accept and handle connections i'm using socket_accept, and then creating a Connection object, adding it to array, and then fetching through all array. But for some reason, when i'm doing $connection::read (which does socket_read) the socket in this objects becomes 0. But when object is constructed, everything is fine, dumping socket returns resource, but dumping the same socket in read() throws warnings, because socket is 0. Here some code

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

There are 0 best solutions below