简体   繁体   English

PHP线程化TCP套接字服务器

[英]PHP threaded TCP socket server

I'm trying to set up a threaded TCP server using the pthread extension for PHP. 我正在尝试使用用于PHP的pthread扩展来设置线程化TCP服务器。 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. 但是,读取客户端发送的数据成功后返回false,并且此后仍在运行。 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? 然后,如何结束$clients数组中的客户端特定类? Dumping this variable gives me "NULL" in the class. 转储此变量在类中给我“ NULL”。

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. 将$ clients上正在运行的var更改为false以完成线程,对不起,我的英语语言是haahha。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM