2011-06-07 242 views
1

這個套接字服務器工作正常,但不知道如何檢查客戶端是否仍然連接,如果沒有關閉連接 任何機構可以幫助檢查客戶端是否仍然連接,如果沒有如何關閉該連接php套接字服務器檢查客戶端是否連接

感謝

<?php 
    // PHP SOCKET SERVER 

// Configuration variables 
    $host = "127.0.0.1"; 
    $port = 3000; 
    $max = 5000; 
    $client = array(); 

    // No timeouts, flush content immediatly 
    @set_time_limit(0); 
    ob_implicit_flush(); 

    // Server functions 
    // Create socket 
    $sock = @socket_create(AF_INET, SOCK_STREAM, 0) or die("[" . date('Y-m-d H:i:s') . "] Could not create socket\n"); 
    // Bind to socket 
    socket_bind($sock, $host, $port) or die("[" . date('Y-m-d H:i:s') . "] Could not bind to socket\n"); 
    // Start listening 
    socket_listen($sock) or die("[" . date('Y-m-d H:i:s') . "] Could not set up socket listener\n"); 

    rLog("Server started at " . $host . ":" . $port); 
    // Server loop 
    while (true) { 
     socket_set_block($sock); 
     // Setup clients listen socket for reading 
     $read[0] = $sock; 
     for ($i = 0; $i < $max; $i++) { 
      if (@$client[$i]['sock'] != null) 
       $read[$i + 1] = $client[$i]['sock']; 
     } 
     // Set up a blocking call to socket_select() 
     $ready = socket_select($read, $write = null, $except = null, $tv_sec = null); 
     // If a new connection is being made add it to the clients array 
     if (in_array($sock, $read)) { 
      for ($i = 0; $i < $max; $i++) { 
       if (@$client[$i]['sock'] == null) { 
        if (($client[$i]['sock'] = socket_accept($sock)) < 0) { 
         rLog("socket_accept() failed: " . socket_strerror($client[$i]['sock'])); 
        } else { 

         rLog("Client #" . $i . " connected"); 
        } 
        break; 
       } elseif ($i == $max - 1) { 
        rLog("Too many clients"); 
       } 
      } 
      if (--$ready <= 0) 
       continue; 
     } 
     for ($i = 0; $i < $max; $i++) { 
      if (in_array(@$client[$i]['sock'], $read)) { 
       $input = socket_read($client[$i]['sock'], 1024); 
       $n = trim($input); 
       if ($input) { 
        // Strip whitespaces and write back to user 
        // Respond to commands 
        /*$output = ereg_replace("[ \t\n\r]","",$input).chr(0); 
        socket_write($client[$i]['sock'],$output);*/ 

        $processRe = processRequest($input); 
        sendMessage($client[$i]['sock'],$processRe); 

       } 
      } else { 

       //if($client[$i]['sock']!=null){ 
       // Close the socket 
       //socket_close($client[$i]['sock']); 
       //unset($client[$i]); 
       //rLog("Disconnected(1) client #".$i); 
       //} 
      } 
     } 
    } 
socket_close($sock); 
?> 

回答

0

當客戶端緊密結合,然後socket_select funcion將返回和指定的套接字句柄的客戶,當你調用socket_read你會得到將可用於socket_readFALSE,這意味着客戶端關閉連接。

但是,當客戶端連接時,您可以通過在其客戶端套接字句柄上調用socket_close函數來關閉連接。