How does facebook, gmail send the real time notification?

前端 未结 5 1000
梦毁少年i
梦毁少年i 2020-11-22 09:55

I have read some posts about this topic and the answers are comet, reverse ajax, http streaming, server push, etc.

How does incoming mail notification on Gmail works

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 10:47

    One important issue with long polling is error handling. There are two types of errors:

    1. The request might timeout in which case the client should reestablish the connection immediately. This is a normal event in long polling when no messages have arrived.

    2. A network error or an execution error. This is an actual error which the client should gracefully accept and wait for the server to come back on-line.

    The main issue is that if your error handler reestablishes the connection immediately also for a type 2 error, the clients would DOS the server.

    Both answers with code sample miss this.

    function longPoll() { 
            var shouldDelay = false;
    
            $.ajax({
                url: 'poll.php',
                async: true,            // by default, it's async, but...
                dataType: 'json',       // or the dataType you are working with
                timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
                cache: false
    
            }).done(function (data, textStatus, jqXHR) {
                 // do something with data...
    
            }).fail(function (jqXHR, textStatus, errorThrown ) {
                shouldDelay = textStatus !== "timeout";
    
            }).always(function() {
                // in case of network error. throttle otherwise we DOS ourselves. If it was a timeout, its normal operation. go again.
                var delay = shouldDelay ? 10000: 0;
                window.setTimeout(longPoll, delay);
            });
    }
    longPoll(); //fire first handler
    

提交回复
热议问题