[PHP] 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为读取没超时

eof为是否已经到了文件尾,如果是长连接这里是不会到达文件尾的,http协议这种短连接会读完后连接就结束了