Server-side PHP event page not loading when using while loop

余生颓废 提交于 2019-12-02 17:56:40

问题


I have a file named handler.php which reads data from a text file and pushes it to a client page.

Relevant client code:

<script>
if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("handler.php");
    source.onmessage = function(event) {
        var textarea = document.getElementById("subtitles");
        textarea.value += event.data;
        textarea.scrollTop = textarea.scrollHeight;

    };
} else {
    document.getElementById("subtitles").value = "Server-sent events not supported.";
}
</script>

Handler.php code:

$id = 0;
$event = 'event1';
$oldValue = null;

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');

while(true){

    try {
        $data = file_get_contents('liveData.txt');
    } catch(Exception $e) {
        $data = $e->getMessage();
    }

    if ($oldValue !== $data) {
        $oldValue = $data;
        echo 'id: '    . $id++  . PHP_EOL;
        echo 'event: ' . $event . PHP_EOL;
        echo 'retry: 2000'      . PHP_EOL;
        echo 'data: '  . json_encode($data) . PHP_EOL;
        echo PHP_EOL;

        @ob_flush();
        @flush();
        sleep(1);  
        }

  }

When using the loop, handler.php is never loaded so the client doesn't get sent any data. In the Chrome developer network tab, handler.php is shown as "Pending" and then "Cancelled". The file itself stays locked for around 30 seconds.

However, if I remove the while loop (as shown below), handler.php is loaded and the client does receive data (only once, even though the liveData.txt file is constantly updated).

Handler.php without loop:

$id = 0;
$event = 'event1';
$oldValue = null;

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');

try {
    $data = file_get_contents('liveData.txt');
} catch(Exception $e) {
    $data = $e->getMessage();
}

if ($oldValue !== $data) {
    $oldValue = $data;
    echo 'id: '    . $id++  . PHP_EOL;
    echo 'event: ' . $event . PHP_EOL;
    echo 'retry: 2000'      . PHP_EOL;
    echo 'data: '  . json_encode($data) . PHP_EOL;
    echo PHP_EOL;

    @ob_flush();
    @flush();

    }

I'm using SSE as I only need one-way communication (so websockets are probably overkill) and I really don't want to use polling. If I can't sort this out, I may have to.


回答1:


The client side of the SSE connection looks OK as far as I can tell - though I moved the var textarea..... outside of the onmessage handler.

UPDATE: I should have looked closer but the event to monitor is event1 so we need to set an event listener for that event.

<script>
    if( typeof( EventSource ) !== "undefined" ) {
        var url = 'handler.php'

        var source = new EventSource( url );
        var textarea = document.getElementById("subtitles");


        source.addEventListener('event1', function(e){
            textarea.value += e.data;
            textarea.scrollTop = textarea.scrollHeight;
            console.info(e.data);
        },false );

    } else {
        document.getElementById("subtitles").value = "Server-sent events not supported.";
    }
</script>

As for the SSE server script I tend to employ a method like this

<?php
    /* make sure the script does not timeout */
    set_time_limit( 0 );
    ini_set('auto_detect_line_endings', 1);
    ini_set('max_execution_time', '0');

    /* start fresh */
    ob_end_clean();


    /* ultility function for sending SSE messages */
    function sse( $evtname='sse', $data=null, $retry=1000 ){
        if( !is_null( $data ) ){
            echo "event:".$evtname."\r\n";
            echo "retry:".$retry."\r\n";
            echo "data:" . json_encode( $data, JSON_FORCE_OBJECT | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS );
            echo "\r\n\r\n";
        }
    }



    $id = 0;
    $event = 'event1';
    $oldValue = null;

    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('X-Accel-Buffering: no');





    while( true ){
        try {
            $data = @file_get_contents( 'liveData.txt' );
        } catch( Exception $e ) {
            $data = $e->getMessage();
        }

        if( $oldValue !== $data ) {

            /* data has changed or first iteration */
            $oldValue = $data;

            /* send the sse message */
            sse( $event, $data );

            /* make sure all buffers are cleansed */
            if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
            @flush();           
        }



        /* 
            sleep each iteration regardless of whether the data has changed or not.... 
        */
        sleep(1);
    }



    if( @ob_get_level() > 0 ) {
        for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
        @ob_end_clean();
    }
?>



回答2:


When using the loop, handler.php is never loaded so the client doesn't get sent any data. In the Chrome developer network tab, handler.php is shown as "Pending" and then "Cancelled". The file itself stays locked for around 30 seconds.

This is because the webserver (Apache) or the browser or even PHP itself cancel the request when there is no response within 30 seconds.

So I guess the flushing does not work, try to actively start and end the buffer without using @ functions so you get a clue when there is an error.

// Start output buffer
ob_start();

// Write content
echo ''; 

// Flush output buffer
ob_end_flush();



回答3:


I think you have a problem with the way the web works. The PHP code doesn't run in your browser - it just creates something that the web server hands off to the browser over the wire.

Once the page is loaded from the server that's it. You will need to implement something that polls for changes.

One way I've done this is to put the page in a loop that refreshes and therefore fetches the page again with the new data every second or so (but this could seriously overload your server if there's a lot of folks on that page).

The only other solution is to use push technology and a javascript framework that can take the push and repopulate the relevant parts of the page, or a javascript loop on a timer that pulls the data.




回答4:


(Posted solution on behalf of the question author).

Success! While debugging for the nth time, I decided to go back to basics and start again. I scrapped the loop and reduced the PHP code to a bare minimum, but kept the client-side code RamRaider provided. And now it all works wonderfully! And by playing around with the retry value, I can specify exactly how often data is pushed.

PHP (server side):

 <?php

    $id = 0;
    $event = 'event1';
    $oldValue = null;

    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('X-Accel-Buffering: no');

    try {
        $data = file_get_contents('liveData.txt');
    } catch(Exception $e) {
        $data = $e->getMessage();
    }

    if ($oldValue !== $data) {
        $oldValue = $data;
        echo 'id: '    . $id++  . PHP_EOL;
        echo 'event: ' . $event . PHP_EOL;
        echo 'retry: 500'      . PHP_EOL;
        echo "data: {$data}\n\n";
        echo PHP_EOL;

        @ob_flush();
        @flush();

        }

  ?>

Javascript (client side):

<script>
    if ( typeof(EventSource ) !== "undefined") {
        var url = 'handler.php'

        var source = new EventSource( url );
        var textarea = document.getElementById("subtitles");


        source.addEventListener('event1', function(e){
            textarea.value += e.data;
            textarea.scrollTop = textarea.scrollHeight;
            console.info(e.data);
        }, false );

    } else {
        document.getElementById("subtitles").value = "Server-sent events not supported.";
    }
</script>


来源:https://stackoverflow.com/questions/52650748/server-side-php-event-page-not-loading-when-using-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!