How to make all connected browsers reload initiated by a server-side event

前端 未结 7 1374
忘掉有多难
忘掉有多难 2020-12-19 17:42

Suppose there is a webpage with dynamically generated content -- say a div containing the current number of connected browsers. When the count changes on the server I want a

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 18:23

    Here's how to do server-push using ajax long-polling. The browser makes an ajax request which initiates server-side self-polling. The ajax request remains open, waiting for a response until the file changes, and as soon as it gets a response, it makes a new long-polling request.

    Here's what it looks like with jQuery and php, implementing the example of live-updating a div in the html showing the number of clients currently connected:

    index.html:

    
    
    Comet Test
      
      
    
    
      Number of connected users: 
    0

    longpolling.js:

    $(document).ready(function() { connectToServer(1); });
    
    function connectToServer( incp ) {
      $.get("LongPolling.php",
            { inc: incp },
            function(resp) {
              $('#total').html(resp);
              connectToServer(0);
            }
           );
    }
    

    LongPolling.php:

    
    

    NOTE: This does not track disconnects, so it's more like live-tracking the total number of pageviews. See Running server-side function as browser closes for info on keeping track of browser disconnects, ie, server-side action on client disconnect.

提交回复
热议问题