1

I am trying to create a chat for my website.

To load the new data, i run a function every 1.5''.

If i use asynchronous mode, my website is fast, my server does not crash, but browser freezes until the response.

When i use synchronous mode, my server crashes after a while, and i have to restart Apache (! ?).

I thought that i was requesting too much data and my (virtual) server crashes, but why in asynchronous mode works fine ?

function loadchat() {
    xmllive.open('GET','live.php', false);
    xmllive.send(null);
    myelemen('dcdd').innerHTML = xmllive.responseText;
}

function loadchatv() {
    xmllive.onreadystatechange=function() {
        if (xmllive.readyState==4 && xmllive.status==200){
        myelemen('dcdd').innerHTML = xmllive.responseText;
    }
}

xmllive.open('GET','live.php', true);
xmllive.send();

Thank you for your answer, MMM. Since your response, i read about your suggestions. (http://dsheiko.com/weblog/websockets-vs-sse-vs-long-polling).

I figured that, in Long Pooling the server makes a loop until finds new data and only then browser receives and makes a new request.

So, tell me please, what do you think about this solution (simplified):

/////////// html file //////////////

<script type="text/javascript" charset="utf-8">

var xmlff;
if (window.XMLHttpRequest) {
    xmlff=new XMLHttpRequest();
} else {
    xmlff=new ActiveXObject("Microsoft.XMLHTTP");
}

   function waitForMsg(){
    xmlff.onreadystatechange=function() {
        if (xmlff.readyState==4 && xmlff.status==200){
            document.getElementById('messages').innerHTML = xmlff.responseText ;
             setTimeout('waitForMsg()', 1000 );
        }
    }
    xmlff.open('GET','msgsrv.php' ,true);
    xmlff.send();
}

</script>
</head>
<body>
    <div id="messages">
    </div>

<script type=text/javascript>
waitForMsg()
</script>
</body>
</html>

/////// php file ///////////

<?

do {
    sleep(3);
    $result = mysql_query("SELECT message FROM chat ");
    while ($row = mysql_fetch_array($result)){
        $msg .= $row[0];
    }

} while (mysql_num_rows($result) == 0);


    header("HTTP/1.0 200");
    print $msg;

?>

Thanks in advance.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • If you're refreshing every 1.5 seconds, this is not a good solution and you should try something else. – MMM Feb 23 '12 at 13:00
  • XMLHttpRequest is not a good solution for refreshing ? – Vagelis Labos Feb 23 '12 at 19:01
  • Depending on which browsers you want to support you should either use WebSockets (modern browsers) or Long Pulling (most other browsers). Refreshing every 1.5 is way to frequent and your server will not cope with a lot of users. – MMM Feb 23 '12 at 20:40

0 Answers0