dszpyf4859 2015-07-16 16:01
浏览 74

PHP线程TCP套接字服务器

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.

  • 写回答

1条回答 默认 最新

  • duancaishun4812 2016-02-16 08:48
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题