Chat system in php with long pool, how to send and get msg together without so much delay time -
im developing chat aplication in php client using long polling. when user send msgs woud .abort() getmsg() function , restart in on sendmsg() sucess (ajax call), if user send repeatedly msgs, getmsg() fired multiple times same parameters, , if other user sending msgs too, got repeatedly same msgs. got way around it, without .abort() getmsg() in sendmsg() works (ajax take care of both calls). when user send repeatedly msgs, need wait in sleep() loop (getmsg()) msgs, if there word in each. there way make abort() fire 1 time on consecutive msgs, or how make sleep() go lower (less seconds) when finds message? wouldt take of server check everytime? thank
s in advance, sorry long text. here`s functions:
php
getmsg() (a php file, 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)) { messages , put in var/array; } json_encode msgs
sendmsg()
query insert textarea value in 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 $(this).val(''); $(".div").append(msg); // }, success: function(html){ // getmsg(); // commented cause i`m not using } });
it`s resumed, take out appending data part, make better read. sendmsg() in javascript append textarea value chat , them send db php when user press enter , textarea have text (i take out part better reading). getmsg() gets on while loop checking if there existing msgs using mysql_num_rows , echo them if any.
i think can fixed using cleartimeout
. try code.
function sendmsg()
// define variable named `pollqueue` outsode of function var pollqueue = false; // send message $.ajax({ type: "post", url: "sendmsg.php", data: { msg : msg, : }, context: this, cache: false, beforesend: function() { // check if getmsg in queue if ( pollqueue ) { // if clear queue cleartimeout( pollqueue ); } if ( jack ) { jack.abort(); } $(this).val(''); $(".div").append( msg ); }, success: function( html ) { // add queue pollqueue = settimeout( getmsg, 3000 ); } });
Comments
Post a Comment