PHP fwrite停止写入套接字文件指针

时间:2010-07-22 12:59:14

标签: php sockets lighttpd fwrite

我有以下PHP代码用于写入使用$fp打开的文件指针fsockopen

syslog(LOG_INFO, "Write " . strlen($buf) . " bytes to socket:");

$bytes = 0;
while ($bytes < strlen($buf) && ($w = @fwrite($fp, substr($buf, $bytes))))
{
    syslog(LOG_INFO, "  - " . $w . " bytes written to socket");
    $bytes += $w;
}

if ($bytes != strlen($buf))
{
    syslog(LOG_INFO, "error while writing to socket");
    exit();
}

只要$buf的大小足够小,此代码就可以正常工作。无法完全写入大量数据。我得到以下输出:

Write 4900360 bytes to socket:
  - 11096 bytes written to socket
error while writing to socket

顺便说一句。 fwrite的返回值为0而不是false

有人知道可能是什么问题吗?非常感谢您的回答

在fwrite前面删除@时,我收到以下注意事项:

Notice: fwrite(): send of 8192 bytes failed with errno=104 Connection reset by peer in /root/test.php on line 10

Notice: fwrite(): send of 8192 bytes failed with errno=32 Broken pipe in /root/test.php on line 10

我只是嗅了一下TCP Stream,我发现,我得到了一个

HTTP/1.1 413 Request Entity Too Large

这个问题有什么问题吗?我使用lighttpd / 1.4.22服务器

1 个答案:

答案 0 :(得分:0)

试试这个

syslog(LOG_INFO, "Write " . strlen($buf) . " bytes to socket:");

$bytes = 0;
do
{
    $w = fwrite($fp, substr($buf, $bytes));
    $bytes += $w;
            syslog(LOG_INFO, "written: ".$w);
    if ($w === 0)
    {
        // end of write
        break;
    }
    if ($w === false)
    {
             syslog(LOG_INFO, "error while writing to socket");
             exit();
    }
} while (true);

我相信你的while循环是以前的问题,并没有像假设那样返回true等等。

查看它何时停止写入