2009-10-09 36 views
5

我负责用PHP编写的API的后端部分,主要由Flash客户端使用。现在发生的事情是:Flash客户端进行调用,后端加载必要的数据,进行必要的处理和后处理,记录和缓存,然后将结果返回给客户端。PHP + gzip:关闭连接并继续执行

我希望发生的事情是尽快将数据返回给客户端,关闭连接,然后完成客户端不必关心的所有事情。这可能会使API看起来更加敏感。这里继建议:

http://php.net/manual/en/features.connection-handling.php

实际工作,但我不得不关闭gzip编码,以使其发挥作用,这是不是很实用。我们在apache中使用mod_deflate,所以一个适用于此的解决方案将是理想的,但如果需要,我还会考虑使用不同的方法来gzip我们的内容。

似乎像应该有办法让阿帕奇知道“我送你所有我要发送的数据,”但我似乎无法找到这样的事情。

对于那些想知道的是,我可以尽早刷新结果,但Flash客户端在连接关闭之前不会处理它们。

回答

3

你可以尝试把它分成两页。

在第一页中,执行必要的处理,然后通过curl和die()加载第二页。

这将导致第一页完成并关闭,独立于第二页处理。

即:

第1页:

第2页:

<?php 

// Do other stuff.... 

?> 

http://www.php.net/curl

+0

感谢。我意识到这个问题的一些解决方法,比其他更优雅,但我真的想找到一种方法告诉Apache停止等待输出并关闭连接。 :) –

0

有通过将你想要的代码是一种黑客要做到这一点在通过注册的回拨方法内关闭连接后执行

+0

哦,有光泽!我明天会试试。 –

+0

没有运气。下面列出了额外的废话,并使用完整的执行时间来关闭使用mod_deflate时的连接: function sleepLo​​ngTime(){print“you can see this”;睡眠(30); } ob_end_clean(); register_shutdown_function('sleepLo​​ngTime'); header(“Connection:close \ r \ n”); ignore_user_abort(true); ob_start(); echo('Text user will see'); ob_end_flush(); flush(); ob_end_clean(); die(); –

0

@ Theo.T因为评论系统缺胳膊少腿的废话了我的代码,我在这里张贴:

没有运气。下面打印出多余的废话,并采取充分的执行时间使用mod_deflate模块时关闭连接:

function sleepLongTime() { 
    print "you can't see this"; 
    sleep(30); 
} 
ob_end_clean(); 
register_shutdown_function('sleepLongTime'); 
header("Connection: close\r\n"); 
ignore_user_abort(true); 
ob_start(); 
echo ('Text user will see'); 
ob_end_flush(); 
flush(); 
ob_end_clean(); 
die(); 
0
set_time_limit(0); 
header("Connection: close"); 
header("Content-Length: " .(strlen($stream)+256)); 
ignore_user_abort(true); 

echo $stream; 
echo(str_repeat(' ',256)); 
@ob_flush(); 
@flush(); 
@ob_end_flush(); 

your_long_long_long_long_function_here(); 

这将告诉用户关闭一旦所有的$stream接收到连接。但要注意不要header部分你知道之前的任何回音:P

如果您要发送的二进制数据(SWF),你可能需要删除“256”和echo(str_repeat(' ',256));但在这种情况下,代码“可能”会失败如果发送的数据小于256字节。

-1

今天我也遇到这种情况,周围的一些测试后,我发现这样工作的:

两个步骤:

  1. 确保PHP脚本输出不是用gzip编码,该解决方案可以参考这个link

    <IfModule mod_env.c>
    SetEnvIfNoCase Request_URI "\.php$" no-gzip dont-vary
    </IfModule>

添加上面.htaccess文件PRJ网站下,则避免阿帕奇gzip的,它会自动。

  1. 至于有些人说在features.connection-handling.php

    set_time_limit(0); 
    ignore_user_abort(true);  
    // buffer all upcoming output - make sure we care about compression: 
    if(!ob_start("ob_gzhandler")) 
        ob_start();   
    echo $stringToOutput;  
    // get the size of the output 
    $size = ob_get_length();  
    // send headers to tell the browser to close the connection  
    header("Content-Length: $size"); 
    header('Connection: close');  
    // flush all output 
    ob_end_flush(); 
    ob_flush(); 
    flush();  
    // close current session 
    if (session_id()) session_write_close(); //close connection 
    
    // here, do what you want. 
    
+0

他要求gzip,你给一个没有gzip的答案......这没有帮助。 – brunoais