最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Server-sent events: How do you automatically reconnect in a cross-browser way? - Stack Overflow

programmeradmin0浏览0评论

I implement some code to query the database for any changes and to send an event. Here's the code of my PHP script

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

//****Some code here to query the database

echo "event: message\n";
echo "data: change_from_database \n";
echo "\n\n";
ob_flush();
flush();

I'm relying on the browser to automatically reconnect each time the connection closes, so I don't implement any loop on my server code. In addition, I learned from this thread that implementing an infinite loop has many disadvantages.

So everything works fine client-side: the browser reconnects each time the connection closes and an event is fired each time the server sends one; well except for Firefox (40.0.2) which doesn't reconnect. I know it doesn't because I wrote some JavaScript error checking code to test this:

var evtSource = new EventSource("../sse.php");
evtSource.onerror = function(event){
    var txt;
    switch( event.target.readyState ){
    case EventSource.CONNECTING:
        txt = 'Reconnecting...';
        break;
    }
    console.log(txt);
}

So after like each second, the console on chrome for example logs "Reconnecting". Firefox on the other hand reconnects once and never does so again.

How do I write code to make this work on Firefox, and perhaps other browsers which support server-sent events but don't reconnect automatically?

I implement some code to query the database for any changes and to send an event. Here's the code of my PHP script

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

//****Some code here to query the database

echo "event: message\n";
echo "data: change_from_database \n";
echo "\n\n";
ob_flush();
flush();

I'm relying on the browser to automatically reconnect each time the connection closes, so I don't implement any loop on my server code. In addition, I learned from this thread that implementing an infinite loop has many disadvantages.

So everything works fine client-side: the browser reconnects each time the connection closes and an event is fired each time the server sends one; well except for Firefox (40.0.2) which doesn't reconnect. I know it doesn't because I wrote some JavaScript error checking code to test this:

var evtSource = new EventSource("../sse.php");
evtSource.onerror = function(event){
    var txt;
    switch( event.target.readyState ){
    case EventSource.CONNECTING:
        txt = 'Reconnecting...';
        break;
    }
    console.log(txt);
}

So after like each second, the console on chrome for example logs "Reconnecting". Firefox on the other hand reconnects once and never does so again.

How do I write code to make this work on Firefox, and perhaps other browsers which support server-sent events but don't reconnect automatically?

Share Improve this question edited May 23, 2017 at 11:46 CommunityBot 11 silver badge asked Aug 18, 2015 at 18:04 Cedric IpkissCedric Ipkiss 6,3377 gold badges49 silver badges76 bronze badges 6
  • 2 stackoverflow.com/questions/11077857/… – Matt Commented Feb 21, 2016 at 16:03
  • Thanks, @mkaatman, but that thread explains what technologies like SSE do. I know a little of what each of these technologies do, and that's why I'm having problems with one of them – Cedric Ipkiss Commented Feb 21, 2016 at 17:04
  • Any chance you can switch to web sockets? – Matt Commented Feb 21, 2016 at 17:09
  • I learned websockets are easier and best with node.js. Problem is with none of my web projects running on dedicated servers, I've run into difficulties using node.js. But it's something I'm willing and ready to dedicate all my time on, if it's a good technology. – Cedric Ipkiss Commented Feb 21, 2016 at 17:14
  • Can you test your code with header('Transfer-Encoding: identity'); ? I don't know will it helps or not, just suggestion. – Wizard Commented Feb 25, 2016 at 2:44
 |  Show 1 more comment

3 Answers 3

Reset to default 6 +50

With the recent version of the Firefox browser (44.0.2), your code works perfectly. However, you can reinitialize your EventSource object in the error handler like this:

var evtSource = new EventSource("../sse.php");
var evtSourceErrorHandler = function(event){
    var txt;
    switch( event.target.readyState ){
        case EventSource.CONNECTING:
            txt = 'Reconnecting...';
            break;
        case EventSource.CLOSED:
            txt = 'Reinitializing...';
            evtSource = new EventSource("../sse.php");
            evtSource.onerror = evtSourceErrorHandler;
            break;
    }
    console.log(txt);
}

But I strongly do not recommend you to do this because your code doesn't use benefits of keeping the connection alive (as you wrote, you are aware of infinite loop) so browser does simple polling (you can see this in then network tab). I don't see any reason to use SSE over AJAX without keeping a permanent connection, which is obviously hard to maintain with PHP. So I assume using simple AJAX polling in this situation.

You could use a polyfill like this one https://github.com/Yaffle/EventSource which should add the event source functionality to unsupported browsers.

Ran a test with your code on my site and everything works as expected with Firefox 44.0.2 and php 5.5. I did run into something interesting on the Mozilla dev network though that states you can't necessarily tell what the error message was on Firefox past v22. Perhaps your switch statement in the error checking that is what's letting you down. Here's a link to the article. Check out the error handling section.

My php code is identical to yours. Just in case I did something different, here's my html code.

<!DOCTYPE>
<html>
<head>
    <title>SSE Test</title>
    <meta charset="utf-8" />
    <script>
      var evtSource = new EventSource("sse.php");
      evtSource.onerror = function(event){
        var txt;
        switch( event.target.readyState ){
           case EventSource.CONNECTING:
               txt = 'Reconnecting...';
               break;
        }
        console.log(txt);
      };
    </script>
  </head>
  <body></body>
</html>
发布评论

评论列表(0)

  1. 暂无评论