【发布时间】:2015-10-22 12:38:45
【问题描述】:
我正在使用以下 sn-p 写入服务器。
$fp = connect();
$sent_requests = 0;
function connect() {
$addr = gethostbyname("example.com");
$fp = fsockopen("$addr", 80, $errno, $errstr);
socket_set_blocking( $fp, false );
if (!$fp) {
echo "$errstr ($errno)<br />\n";
exit(1);
} else{
echo "Connected\n";
return $fp;
}
}
function sendTestCalls($load){
global $fp, $sent_requests;
if(!$fp){
echo "reconnecting";
$sent_requests = 0;
//echo stream_get_contents($fp) . "\n";
fclose($fp);
$fp = connect();
}
$data = "POST /test HTTP/2.0\r\n";
$data.= "Host: example.com\r\n";
$data.= "Content-Type: application/json\r\n";
$data.= "Content-Length: ".strlen($load)."\r\n";
$data.= "Connection: Keep-Alive\r\n";
$data.= "xYtU87BVFluc6: 1\r\n";
$data.= "\r\n" . $load;
$bytesToWrite = strlen($data);
$totalBytesWritten = 0;
while ($totalBytesWritten < $bytesToWrite) {
$bytes = fwrite($fp, substr($data, $totalBytesWritten));
$totalBytesWritten += $bytes;
}
$sent_requests++;
}
$time = time();
for($i=0; $i<1000; $i++) {
sendTestCalls('{"justtesting": "somevalue"}');
}
fclose($fp);
$time_taken = time() - $time;//might be a bit inaccurate
echo "Time Taken: " . $time_taken . "\n";
当我在我的服务器上检查我的访问日志时,收到的发布请求少于 1000 个(范围为 0 到 900)。我在这里做错了什么?
EDIT1
我想我的套接字正在超时。我应该怎么做才能检查它是否在这种情况下断开连接重新连接。我尝试使用stream_get_meta_data($fp),但没有效果。
【问题讨论】:
-
你试过使用socket_set_timeout吗?请在此处查看示例php.net/manual/en/function.stream-set-timeout.php 以检查套接字超时
-
是的,但这也只能在一段时间内有效,直到服务器关闭连接。之后一切都以同样的方式进行。
-
您是否查看过我提供链接的超时处理示例?