Система за чат в php с дълъг пул, как да изпращате и получавате съобщения заедно без толкова много време на забавяне

im currently developing a chat aplication in php to a client using long polling. When the user send msgs i woud .abort() the getmsg() function and restart in on sendmsg() sucess (ajax call), but if the user send repeatedly msgs, the getmsg() get fired multiple times with same parameters, and if the other user is sending msgs too, i got repeatedly the same msgs. I got a way around it, without .abort() the getmsg() in sendmsg() it works well (ajax take care of both calls). But when the user send repeatedly msgs, i need to wait in the sleep() loop (getmsg()) to get all the msgs, even if there only a word in each. Is there a way to make the abort() fire just one time on consecutive msgs, or how i could make the sleep() to go lower (less seconds) when it finds a message? Wouldt it take so much of the server to do this check everytime? Thanks предварително, съжалявам за твърде дългия текст. Ето функциите:

PHP

getmsg() (a php file, this is the function)
$aa = mysql_num_rows($chatresult);
$togetmsg = 2;
while($aa == 0 && $tried_times < 6) {

sleep($togetmsg);
$chatresult = mysql_query("query"); 
$aa = mysql_num_rows($chatresult);
$tried_times++;
}

while($crow = mysql_fetch_assoc($chatresult))
{
 get the messages and put in a var/array;       

} 
json_encode the msgs

sendmsg()

 Just a query to insert the textarea value in the table.

JAVASCRIPT

getmsg():

  jack = $.ajax({
        type: "POST",
        url: "getmsg.php",
        data: {friend_chatid: friend_chatid, msg_id: msg_id},
        dataType: 'json',
        context: this,
        async: true,
        cache: false,
        timeout:30000,

        success: function(html){      
            $(this).find(".div").append(message);
            msg_id = 0;

            var _this = $(this);     
            setTimeout(
                getmsg, /* Request next message */
                1000 /* ..after 1 seconds */
            );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
         if(textStatus==="abort" || errorThrown==="abort") {
     //   alert(textStatus);
    } else {
            setTimeout(
                getmsg, 
                3000);
    }



        }
    });

SENDMSG()

$.ajax({
type: "POST",
url: "sendmsg.php",
data: {msg: msg, to: to},
context: this,
cache: false,
beforeSend: function () {
//   jack.abort(); // Commented cause i`m not using it now
$(this).val('');
    $(".div").append(msg); //

 },
success: function(html){
    //    getmsg(); // Commented cause i`m not using it now
  }
});  

Възобновено е, изваждам частта с добавяне на данни, за да се чете по-добре. Sendmsg() в javascript добавя стойността на текстовото поле към чата и го изпраща в db с php, когато потребителят натисне enter и текстовото поле има текст (махам тази част за по-добро четене). Getmsg() влиза в цикъл while, като проверява дали има съществуващи съобщения с помощта на mysql_num_rows и ги повтаря, ако има такива.


person sagits    schedule 23.08.2013    source източник


Отговори (1)


Мисля, че може да се поправи с clearTimeout. Просто опитайте този код.

Функция sendmsg()

// define a variable named `pollQueue` outsode of your function
var pollQueue = false;

// send message
$.ajax({
  type: "POST",
  url: "sendmsg.php",
  data: { msg : msg, to : to },
  context: this,
  cache: false,
  beforeSend: function() {
    // Check if getmsg is in queue
    if ( pollQueue ) {
      // if so clear the queue
      clearTimeout( pollQueue );
    }
    if ( jack ) {
      jack.abort();
    }
    $(this).val('');
    $(".div").append( msg );
  },
  success: function( html ) {
    // add to queue
    pollQueue = setTimeout( getmsg, 3000 );
  }
});
person bystwn22    schedule 23.08.2013
comment
какво е жак в твоя пример? - person ahmad; 24.08.2013
comment
Моля, прочетете въпроса - person bystwn22; 24.08.2013
comment
в началото не го забелязах, съжалявам. - person ahmad; 24.08.2013
comment
Благодаря, опитах и ​​не се получи, получавам едно и също съобщение многократно. Опитах с settimeout преди, но без да използвам var (pollQueue), същите резултати. - person sagits; 24.08.2013