使用单一连接编写多个帖子请求 – PHP

我正在使用以下代码段写入服务器.

$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),但它没有效果.

解决方法

尝试在每个请求之前插入此内容:

    $info = stream_get_meta_data($fp);    if($info [‘timed_out’]){        FCLOSE($FP);        $fp = connect();    }

相关文章

什么是设计模式一套被反复使用、多数人知晓的、经过分类编目...
单一职责原则定义(Single Responsibility Principle,SRP)...
动态代理和CGLib代理分不清吗,看看这篇文章,写的非常好,强...
适配器模式将一个类的接口转换成客户期望的另一个接口,使得...
策略模式定义了一系列算法族,并封装在类中,它们之间可以互...
设计模式讲的是如何编写可扩展、可维护、可读的高质量代码,...