How to display HTML to the browser incrementally over a long period of time?

前端 未结 8 707
生来不讨喜
生来不讨喜 2020-12-05 11:58

Do I need to pass back any HTTP headers to tell the browser that my server won\'t be immediately closing the connection and to display as the HTML is received? Is there anyt

相关标签:
8条回答
  • 2020-12-05 12:10

    The client will close the connection when it does not receive any data for a certain time. This timeout cannot be influenced by HTTP headers. It is client-specific and usually set to 120 seconds IIRC.

    So all you have to do is send small amounts of data regularly to avoid hitting the timeout.

    0 讨论(0)
  • 2020-12-05 12:10

    I think a more robust solution is a page with a Javascript timer that polls the server for new data. Keeping the response open is not something the HTTP protocol was designed for.

    0 讨论(0)
  • 2020-12-05 12:10

    at the end of your script, use something like this (assuming you had output buffering on by putting ob_start() at the top of your page

    <?php
    
    set_time_limit(0); // Stop PHP from closing script after 30 seconds
    
    ob_start();
    
    echo str_pad('', 1024 * 1024, 'x'); // Dummy 1 megabyte string
    
    $buffer = ob_get_clean();
    
    while (isset($buffer[0])) {
    
    $send = substr($buffer, 0, 1024 * 30); // Get 30kbs bytes from buffer :D
    $buffer = substr($buffer, 1024 * 30); // Shorten buffer
    
    echo $send; // Send buffer
    echo '<br />'; // forces browser to reload contents some how :P
    
    ob_flush(); // Flush output to browser
    flush(); 
    
    sleep(1); // Sleep for 1 second
    
    }
    
    ?>
    

    That script basically outputs 1 megabyte of text at 30kbs (simulated) no matter how fast the user and server connection is.

    0 讨论(0)
  • 2020-12-05 12:12

    Depending on what you are doing, you could just echo as your script proceeds, this will then send the html to the browser as it is echoed.

    0 讨论(0)
  • 2020-12-05 12:13

    Long polling is a common technique to do something like this; to briefly summarise, it works as follows:

    1. The client sends an XHR to the server.

      • If there is data ready, the server returns this immediately.
      • If not, the server keeps the connection open until data does become available, then it returns this.
      • If the request times-out, go back to 1).
    2. The page running on the client receives this data, and does what it does with it.

    3. Go back to 1)

    This is how Facebook implements its chat feature.

    This article also clears up some of the misconceptions of long-polling, and details some of the benefits of doing so.

    0 讨论(0)
  • 2020-12-05 12:18

    Try forever frame (like in gmail)

    All of these technics are just hacks, http isn't designed to do this.

    0 讨论(0)
提交回复
热议问题