2016-11-04 65 views
0

我有代碼如下,使用php7-zts和pthreads。我想知道如何正確清理完成的客戶端,所以我沒有內存泄漏。pthreads如何銷燬完成的套接字連接

<?php 

class Client extends Thread {   
    public function __construct($socket){ 
     $this->socket = $socket; 
     $this->start(); 
    } 
    public function run(){     
     $msgsock = $this->socket; 
     if ($msgsock) { 
      if (false === ($buf = socket_read($msgsock, 2048, PHP_BINARY_READ))) { 
       echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n"; 
      } 

      ...... 

      $write_result = socket_send($msgsock, $result, strlen($result), MSG_EOF); 
      socket_close($msgsock);  
      //finished      
     }    
    } 
} 

... 
//create, bind, and listen $sock 
... 

while(($client = socket_accept($sock))){ 
    $clients[]=new Client($client); 
} 

?> 

回答

0

更換

while(($client = socket_accept($sock))){ 
    $clients[]=new Client($client); 
} 

隨着

while ($client = socket_accept($sock)) 
{ 
    $clients[] = new Client($client); 

    /* Loop through Array Clients and clean done ones to free some memory */ 
    foreach ($clients as $key=>$value) 
    { 
     if ((isset($clients[$key]['done'])) && ($clients[$key]['done'])) 
     { 
      socket_close($clients[$key]['socket']); 
      unset($clients[$key]); 
     } 
    } 
} 

請確保您添加這個 - $>做真正的析構函數,你的客戶端類,允許成品工人的檢測。

class Client extends Thread 
{ 
    public $this->done; 

    public function __construct($socket) 
    { 
     $this->socket = $socket; 
     $this->done = false; 
     $this->start(); 
    } 

    public function __destruct($socket) 
    { 
     $this->done = true; 
    } 

    public function run() 
    { 
     // Your CODE Here! 
    } 
}