Frage

I am new to comet and doing a simple application. My html file looks like

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>testing comet</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="jquery-1.9.0.js"></script>
  </head>
  <body>

<div id="content">
</div>

<p>
  <form action="" method="get" onsubmit="comet.doRequest($('#word').val());$('#word').val('');return false;">
    <input type="text" name="word" id="word" value="" />
    <input type="submit" name="submit" value="Send" />
  </form>
</p>

<script type="text/javascript">
// comet implementation
var Comet = function (data_url) {
  this.timestamp = 0;
  this.url = data_url;  
  this.noerror = true;
//alert(data_url);
  this.connect = function() {
    var self = this;

    $.ajax({
      type : 'get',
      url : this.url,
      dataType : 'json', 
      data : {'timestamp' : self.timestamp},
      success : function(response) {
        self.timestamp = response.timestamp;
        self.handleResponse(response);
        self.noerror = true;          
      },
      complete : function(response) {
        // send a new ajax request when this request is finished
        if (!self.noerror) {
            alert("error");
          // if a connection problem occurs, try to reconnect each 5 seconds
          setTimeout(function(){ comet.connect(); }, 5000);           
        }else {
          // persistent connection
          self.connect(); 
        }

        self.noerror = false; 
      }
    });
  }

  this.disconnect = function() {}

  this.handleResponse = function(response) {
    $('#content').append('<div>' + response.msg + '</div>');
  }

  this.doRequest = function(request) {
      $.ajax({
        type : 'get',
        url : this.url,
        data : {'msg' : request}
      });
  }

}

var comet = new Comet('./backend.php');
comet.connect();
</script>

</body>
</html>

backend.php looks like

<?php
$dr=DIRECTORY_SEPARATOR;
$filename  = dirname(__FILE__).$dr.'data.txt';

// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
  file_put_contents($filename,$msg);
  die();
}

// infinite loop until the data file is not modified
$lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
  usleep(10000); // sleep 10ms to unload the CPU
  clearstatcache();
  $currentmodif = filemtime($filename);
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();

data.txt contains a blank file.

Now my question is

if (!self.noerror) {
      alert("error");

This will execute and showing alert "error" always. But it is working perfectly if I comment that alert part. Is anything wrong ?

When I track the process with firebug, on those requests, getting an fatal error like this.

enter image description here

Any one please help me Thanks in advance

War es hilfreich?

Lösung

The time-out issue will be caused by your while loop failing to exit before PHP exits because the value of the max_execution_time directive has been reached. You could extend this, but do you really want scripts to be running for that long? I'd be more inclined to do more work in the JavaScript - make it request an update every second or so (10ms is far, far too often).

Regarding the alert("error"), be careful where you're setting the value of noerror - do you really want to set it to false at the end of the complete() function? I think you want to change your call to $.ajax() to something more like this (abbreviated):

$.ajax({
    error : function() {
        // the request failed
        setTimeout(function() { comet.connect(); }, 5000);
    },
    success : function(response) {
        // the request succeeded
        self.connect();
    }
});

If you can, remove the noerror variable entirely and use the error() and success() callbacks to house your logic for each scenario, like above.

Andere Tipps

You must edit the backend.php lines;

<?php
   $dr=DIRECTORY_SEPARATOR;
   ini_set('max_execution_time', 300);
   $filename  = dirname(__FILE__).$dr.'data.txt';
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top