不断地发送一些数据点(目标是每秒一次),使用 PHP 中的 POST 请求的无限循环。这些数据高度依赖于时间。如果出现超时,我不关心丢失的数据,只想快速转移到下一个数据点。
最初,我使用了
我还了解到套接字有两种超时类型,所以我将代码更改为使用
最初,我使用了
file_get_contents()
(超时值为1)来进行此 POST 请求,但我遇到了一些问题,本应该超时却没有。我阅读了很多相关问题,普遍认为 file_get_contents()
上的超时未被触发,因为它是一个“读取”超时,而不是“连接”超时。我还了解到套接字有两种超时类型,所以我将代码更改为使用
fsockopen()
。以下是代码片段。 // waaaay up at the top of the file
ini_set("default_socket_timeout", 1); // set default socket connect timeout
//...
// inside the loop
echo("4...");
$url = 'othersite.ie';
$fp = fsockopen($url, 80, $errno, $errstr, 1); // connect timeout of 1
if(!$fp)
{
echo($errno .": ". $errstr);
}
else
{
echo("5...");
stream_set_timeout($fp, 1, 0); // read timeout of 1
$content = http_build_query($data); // array assembled before this snippet
fwrite($fp, "POST /some/address/at/url HTTP/1.1\r\n");
fwrite($fp, "Host: www.examplesite.ie\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
while(!feof($fp))
{
$result = $result . fgets($fp, 1024);
}
echo("6...");
if (empty($result))
{
echo("No result");
}
}
然而,这似乎没有起到任何帮助。我添加了一些echo
语句,以便如果我观察输出,我可以看到延迟发生的位置,而且它一直在“4...”和“5...”之间变化。每个延迟大约十秒钟,它们似乎没有特定的顺序。大多数情况下(超过99%),连接正常,读取正常,我将数据发送到服务器。但至少要试图消除那些10秒钟的停顿。任何帮助都将不胜感激。