EventSource: always getting error

前端 未结 1 589
抹茶落季
抹茶落季 2021-01-20 16:49

To get start with EventSource API I wrote the most scholastic example. The problem is that I\'m always getting error and I can\'t find any useful information ab

相关标签:
1条回答
  • 2021-01-20 17:45

    (TLDR: you are not using the SSE protocol - see second half of this answer.)

    The first thing you need to do is get a proper error message, or at least look at your script is producing. I'd suggest using curl to test your script. From the commandline:

    curl http://127.0.0.1/source.php
    

    (I've assumed both your html and source.php are on your local machine, and not using https; adjust the above if not. Also adjust to add the path to source.php.)

    If that works, or you don't have curl available, look at the developer tools in your browser. Look to see what is happening with the connection to source.php, what is being sent, and what is being received.

    However, there are definitely a couple of ways to improve the PHP script. First prefix the message with "data:" and add the couple of LFs after each message; this is required by the SSE protocol.

    Second, use an infinite loop with a sleep in it (there is never any point having an SSE script that returns one thing and closes - you might as well just use AJAX, in that case). So it would look like this:

    <?php
    header('Content-Type: text/event-stream');
    header('Cache-control: no-cache');
    
    while(true){
        $time = date('r');
        echo "data:Time: $time\n\n";
        @ob_flush();flush();
        sleep(1);
        }
    
    0 讨论(0)
提交回复
热议问题