php - nginx 将数据不完整地传输到 unix 域套接字

标签 php linux nginx unix-socket

我的应用程序在 unix 域套接字 (UDS) 上监听传入数据,而 nginx 使用 PHP 发送数据。发送几 KB 的较小数据 block 可以完美地工作,但一旦达到一定限制,浏览器就会收到错误 504 Gateway Time-out,nginx 日志

upstream timed out (110: Connection timed out) while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /foo/bar.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock", host: "localhost"

套接字仍会获取一些数据(总是减少大约 1.5 MB)并回复,但网络服务器似乎没有收到回复。 是否有任何必须调整的 UDS 流限制或 nginx 变量?

PHP代码:

public function send ($msg)
{
    $str = "{$msg}".chr(27);

    $ret = socket_write($this->socket, $str, strlen($str));

    if ($ret == FALSE)
    {
        return false;
    }
    else
    {
        $response = "";

        while (($chunk = socket_read($this->socket, 2048, PHP_BINARY_READ)) !== FALSE)
        {
            $response .= $chunk;

            if (substr($chunk, -1) == chr(27))
                break;
        }

        //close the connection
        if ($this->connected !== false)
        {
            socket_shutdown($this->socket);
            socket_close($this->socket);
            $this->connected = false;
        }

        return $response;
    }
}

最佳答案

好的,对于陈述者来说,Nginx 与这个问题无关,很明显是 PHP 发送和接收数据。

很可能您的远程系统没有在正确的时间关闭套接字,或者只是花费了很长时间才能响应。

while (($chunk = socket_read($this->socket, 2048, PHP_BINARY_READ)) !== FALSE)
{
    $response .= $chunk;
    if (substr($chunk, -1) == chr(27))
    break;
}

如果远程系统没有关闭连接/套接字并告诉你它将继续尝试读取并等待 2048(位或字节 - 我可以永远不要记住它要求的大小,以确保评论会告知)在读取完成之前要通过的数据或要关闭的套接字。

所以尝试降低读取字节数的一些方法将其设置为 128 之类的东西,在您的套接字中放置一个计时器(需要在 PHP 中进行异步编程)读取,以便在 28 秒后将其终止再给你的代码 2 秒来执行(安全退出)。或使用 set_time_limit 来增加您的时间限制。

如果你确实增加了你的时间限制,你将需要增加允许 nginx 从连接到 PHP 的响应来执行此操作的时间量设置你的 fastcgi_read_timeout

关于php - nginx 将数据不完整地传输到 unix 域套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48095637/

相关文章:

python - 如何在 Linux RHEL 6.6 上安装 docker-compose?

更改 GitLab 端口后 nginx 网关错误

django - Nginx 重定向到默认页面

python - Django:静态/媒体文件不同服务器

php - 我怎样才能使 W3schools php 上传示例工作?

php - 以 .xls 格式而不是制表符分隔格式导出数据

linux - 数字数组之间有两个额外的空间

linux - 从多个文件夹中移动txt文件并重命名

PHP不会更新

php - WHERE IN 语句返回 'where clause' 中的未知列