Mikael H.
Mikael H.

Reputation: 23

PHP threaded TCP socket server

I'm trying to set up a threaded TCP server using the pthread extension for PHP. I know, that it is not supported officially, but I have tried to do something like this:

class luokka extends Thread {
    private $client;
    public function __construct($socket) {
        $this->client = $socket;
        $this->start(); // Starts the threading
    }
    public function run() {
        while (true) {
            $data = socket_read($this->client, 128);
            if ($data === false) {
                // Error, or client disconnection = break
            }
            // ...
        }
    }
}

$clients = array();

while (1) {
    if (($sox = socket_accept($server)) !== false) {
        $clients[] = new luokka($sox);      
    }
}

However, reading the client sent data returns false after a success and is still running after that. Only server is set to non-blocking mode to allow other things as well in main infinite-loop. When I close the client connection from the server, client does not detect it (regarding the false result?). When the client closes the connection, server does not detect it as false while reading. What to do?

Then, how can I remove client specific class from $clients array, when it comes to end? Dumping this variable gives me "NULL" in the class.

Upvotes: 1

Views: 2089

Answers (1)

Sebastian Robles
Sebastian Robles

Reputation: 11

You need close the while with a condition on the Threads.

$this->running = true;    
while $this->running) {
     $data = socket_read($this->client, 128);
     if ($data === false) {
         $this->running = false;       
    }         
}

change the running var on $clients to false for finish the thread, Sorry For my english haahha.

Upvotes: 1

Related Questions