php-fgets()使用套接字读取,仍然无法正常工作 [英] Php - fgets() reading with socket, still not working properly

查看:68
本文介绍了php-fgets()使用套接字读取,仍然无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经花了很多时间解决fgets()问题,但没有成功.我正在通过HTTP套接字从不同来源接收数据.到现在为止,我有更多不同的来源,效果很好.

I've spent a lot of time on this fgets() problems without any success until now. I'm receiving data from different sources through a HTTP socket. It worked fine until now that I have a lot more different sources.

我的目标是摆脱php的执行超时,只知道它在15秒后超时,但继续使用下一个源代码.

My goal is just to get rid of the execution timeout of php, just know that it timed out after 15 seconds but go on with the next source.

这是我的一小段代码:

//This is just from php.net, found out that it works pretty good
$time = time();
while (!($temp = fsockopen($host, $port, $errNo, $errMessage, $timeout)))
{
    if ((time() - $time) >= $timeout)
    {
        socket_close($temp);
        return false;
    }
    sleep(1);
}

    //If PHP returns an error
 if (!($temp)) {
    echo 'Socket could not be opened.<br/>';
    return false;
}

$return = "";

if (!fwrite($temp, $out)) {
    print_r(error_get_last());
    return false;
}

    //Timeout set to 15 seconds
    stream_set_blocking($temp, 0);
    $start = time();

    while ((time() < ($start + 15))) {

        //(Last lines always finishes like this)
        if (substr(trim($return),-9) == '"id":"1"}') {
            break;
        } else {
            $return .= fgets($temp, 512);
        }
    }
    fclose($temp);

经过一些测试,我发现一个非阻塞套接字可以为该代码提供更好的结果,但是在收到4个源的数据后,它仍然处于阻塞状态.(我试图更改顺序,所以它不依赖于源)

After some testing I found out that a non-blocking socket gives way better results for this code, however it is still blocking after data has been received for 4 sources. (I tried to change the order so it is not source-dependent)

我试图使用stream_set_timeout($ temp)并在循环中检查标志的状态,但它不会改变任何事情.

I tried to use stream_set_timeout($temp) and check the state of the flag in the loop but it doesn't change a thing.

我忘了提及它,但是脚本在fgets()所在的行处停止(PHP执行超时为30秒).

I forgot to mention it, but the script is stopping (PHP execution timeout of 30 seconds) at the line with fgets().

有任何线索吗?

干杯!

推荐答案

length 参数的文档> fgets() :

The documentation of the length parameter to fgets():

当读取长度-1个字节,换行符(包含在返回值中)或EOF(以先到者为准)时,读取结束.如果未指定长度,它将一直从流中读取数据,直到到达行尾为止.

在您的情况下,这些条件都无法满足,这将使脚本无限期地等待输入.

None of these conditions will be met in your case, which will let the script wait indefinitely on input.

要利用 stream_set_timeout()设置的套接字超时,可以使用 fread() 而不是 fgets(),它将遵守设置的超时时间.与 fgets()的唯一区别在于, fread()一次不会获取一行,而是整个 length 个字节

To make use of the socket timeout set by stream_set_timeout() you can use fread() instead of fgets(), which will honor the set timeout. The only difference with fgets() is that fread() doesn't fetch a line at a time, but the whole length number of bytes.

这篇关于php-fgets()使用套接字读取,仍然无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆