Setting time interval in HTML5 server sent events

前端 未结 4 833
南旧
南旧 2020-12-15 10:45

I want to send regular updates from server to client. For that I used server-sent event. I\'m pasting the codes below:

Client side

4条回答
  •  春和景丽
    2020-12-15 11:21

    The reason for this behavior (message every 3 seconds) is explained here:

    The browser attempts to reconnect to the source roughly 3 seconds after each connection is closed

    So one way to get message every 100 milliseconds is changing the reconnect time: (in the PHP)

    echo "retry: 100\n\n";
    

    This is not very elegant though, better approach would be endless loop in PHP that will sleep for 100 milliseconds on each iteration. There is good example here, just changing the sleep() to usleep() to support milliseconds:

    while (1) {
        $x=rand(0,1000);
        echo "data:{$x}\n\n";
        flush();
        usleep(100000); //1000000 = 1 seconds
    }
    

提交回复
热议问题