連接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為讀取沒超時
eof為是否已經到了檔案尾,如果是長連接這里是不會到達檔案尾的,http協議這種短連接會讀完后連接就結束了
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/96380.html
標籤:PHP
上一篇:php基礎知識總結
下一篇:swoole加密可破解嗎
