简体   繁体   中英

PHP “PUSH” To Javascript

Right now we have a web application that is ran on a local network where the clients run everything in javascript. In order to make sure everything is in sync these clients currently utilize an AJAX request to the server by sending the last "syncId" that it has recieved. The server then responds with an array tree of commands to get this client up to date. This is executed every second and has yet to cause any issues with network bandwith or latency however we are installing a system in a bigger client next month that may push the limits of this method and I am wondering if it is feasible to have the server "PUSH" the sync events to the clients in real time.

 srvResponse=httpGet("CDSSync.php?sessionKey="+sessionKey+"&lastUpdate="+lastUpdate); if(srvResponse!=0){ syncEvents=srvResponse.split(";"); for(var i=0; i<syncEvents.length; i++){ syncItem=syncEvents[i].split(","); window["syncFunction_"+syncItem[1]](syncItem[2]); lastUpdate=syncItem[0]; } } 

The above is where my system checks for events to be synced where syncItem[0] is a autoIncrement ID, syncItem[1] is a code for the event being handled and syncItem[2] is a parameter for the function. the httpGet function being called although not in this code is just a function that fetches from the server and returns the response.

Take a look at www.firebase.com, you can set up a push service from javascript clients to all others in minutes. Try the simple tutorial first:

<!doctype html>
<html>
  <head>
    <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
    <link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
  </head>
  <body>
    <div id='messagesDiv'></div>
    <input type='text' id='nameInput' placeholder='Name'>
    <input type='text' id='messageInput' placeholder='Message'>
    <script>
      var myDataRef = new Firebase('https://hbw30ob2a8y.firebaseio-demo.com/');
      $('#messageInput').keypress(function (e) {
        if (e.keyCode == 13) {
          var name = $('#nameInput').val();
          var text = $('#messageInput').val();
          myDataRef.push({name: name, text: text});
          $('#messageInput').val('');
        }
      });
      myDataRef.on('child_added', function(snapshot) {
        var message = snapshot.val();
        displayChatMessage(message.name, message.text);
      });
      function displayChatMessage(name, text) {
        $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
        $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
      };
    </script>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM