websocket向指定客户端发送大文件

a810291783

客户端每次只能接收744 KB (761,856 字节)后就自动断开了

以下是在论坛看到的大文件发送例子

<?php
use Workerman\Worker;
require_once './Workerman/Autoloader.php';

$worker = new Worker('http://0.0.0.0:4236');
$worker->onMessage = function($connection, $data)
{
    if($_SERVER == '/favicon.ico')
    {
        return $connection->send("HTTP/1.0 404 Not Found\r\nContent-Length: 0\r\n\r\n", true);
    }
    // 这里发送的是一个大的pdf文件,如果是其它格式的文件,请修改下面代码中http头
    send_file($connection, "/your/path/xxx.pdf");
};

function send_file($connection, $file_name)
{
    if(!is_file($file_name))
    {
        $connection->send("HTTP/1.0 404 File Not Found\r\nContent-Length: 18\r\n\r\n404 File Not Found", true);
        return;
    }

    // ======发送http头======
    $file_size = filesize($file_name);
    $header = "HTTP/1.1 200 OK\r\n";
    // 这里写的Content-Type是pdf,如果不是pdf文件请修改Content-Type的值
    // mime对应关系参见 https://github.com/walkor/Workerman/blob/master/Protocols/Http/mime.types#L30
    $header .= "Content-Type: application/pdf\r\n";
    $header .= "Connection: keep-alive\r\n";
    $header .= "Content-Length: $file_size\r\n\r\n";
    $connection->send($header, true);

    // ======分段发送文件内容=======
    $connection->fileHandler = fopen($file_name, 'r');
    $do_write = function()use($connection)
    {
        // 对应客户端的连接发送缓冲区未满时
        while(empty($connection->bufferFull))
        {
            // 从磁盘读取文件
            $buffer = fread($connection->fileHandler, 8192);
            // 读不到数据说明文件读到末尾了
            if($buffer === '' || $buffer === false)
            {
                return;
            }
            $connection->send($buffer, true);
        }
    };
    // 发生连接发送缓冲区满事件时设置一个标记bufferFull
    $connection->onBufferFull = function($connection)
    {
        // 赋值一个bufferFull临时变量给链接对象,标记发送缓冲区满,暂停do_write发送
        $connection->bufferFull = true;
    };
    // 当发送缓冲区数据发送完毕时触发
    $connection->onBufferDrain = function($connection)use($do_write)
    {
        $connection->bufferFull = false;
        $do_write();
    };
    // 执行发送
    $do_write();
}
Worker::runAll();

请问是不是Nginx配置原因导致的

201 1 0
1个回答

six

你4236是http协议啊,都不是websocket协议。发的数据也是http数据

  • a810291783 2024-03-25

    那个是例子里的,是websocket。protected $socket = 'websocket://0.0.0.0:2345';

  • six 2024-03-25

    发送大文件直接 send(file_get_contents(文件路径)) 就好了

  • a810291783 2024-03-25

    这样发送给客户端后直接就断开了,客户端接收的文件为空。上边的写法还能接收一部分。不知道到底什么原因,可以给个大概的猜测吗

🔝