[PHP] socket客戶端時的超時問題

鏈接socket分爲鏈接超時和讀取超時socket

$sock=stream_socket_client("www.google.com:80", $errno,$errstr,2);    那個數字是鏈接超時 ,好比鏈接google , 2秒就返回錯誤 , 這樣就不會一直等在那了
stream_set_timeout($sock,5);  這個數字是讀取數據的超時
 
stream_get_meta_data 能夠在socket中返回元數據
 
好比下面的測試,由於http協議鏈接完就會被服務端斷掉,因此沒辦法使用長鏈接一直傳輸數據,須要在循環中不停的new對象建立鏈接
for($i=0;$i<1000;$i++){
    $sock=stream_socket_client("www.baidu.com:80", $errno,$errstr,2);  
    stream_set_timeout($sock,5); 
    $meta=stream_get_meta_data($sock);

    var_dump("start",$meta);
    fwrite($sock, "GET / HTTP/1.0\r\n\r\n");

    $buf = '';
    while (true) {
        $s = fread($sock,1024);
        if (!isset($s[0])) {
            break;
        }
        $buf .= $s;
    }
    $meta=stream_get_meta_data($sock);
    var_dump("end",$meta,$sock);
}
string(5) "start"
array(7) {
  ["stream_type"]=>
  string(14) "tcp_socket/ssl"
  ["mode"]=>
  string(2) "r+"
  ["unread_bytes"]=>
  int(0)
  ["seekable"]=>
  bool(false)
  ["timed_out"]=>
  bool(false)
  ["blocked"]=>
  bool(true)
  ["eof"]=>
  bool(false)
}
string(3) "end"
array(7) {
  ["stream_type"]=>
  string(14) "tcp_socket/ssl"
  ["mode"]=>
  string(2) "r+"
  ["unread_bytes"]=>
  int(0)
  ["seekable"]=>
  bool(false)
  ["timed_out"]=>
  bool(false)
  ["blocked"]=>
  bool(true)
  ["eof"]=>
  bool(true)
}
resource(175) of type (stream)

其中的timed_out就是讀取數據的超時,false爲讀取沒超時tcp

eof爲是否已經到了文件尾,若是是長鏈接這裏是不會到達文件尾的,http協議這種短鏈接會讀完後鏈接就結束了測試

相關文章
相關標籤/搜索