1

我使用 php 和 ajax 进行了聊天,并且正在使用 while 循环检查数据库中的新消息。

这是检索消息的代码:

//retrive message

function update(){

$(document).ready(function(){

$.ajax({

async: true,

type: "POST",

url: "listen.php",

success: function(data){

$("#myp").before(data);

},

complete: function(){

window.setTimeout("update();",100);
}

});

});

};


//wating for new message

<?php
include_once("connect.php");

$type="";

while($type!=='n'){


usleep(1000);

$search=mysql_query("SELECT * from chat ORDER BY id DESC LIMIT 1");

$row=mysql_fetch_assoc($search);

$type=$row['type'];

$id=$row['id'];

}

echo $row['message'] . "<br/>";


mysql_query("UPDATE chat SET type='o' WHERE id=$id");


?>

现在这工作正常,php 文件不断检查是否有任何新消息,更新功能在页面加载时启动并等待响应。但它有效吗?如果我要在网站上使用它,恐怕会因为 while 循环而对服务器造成太大压力。有谁知道一种方法,使while循环对服务器更友好?

4

1 回答 1

1

Your hunch is correct. A typical server setup can answer any where between 100-1000 PHP requests per second, so doing 10 requests a second per client is going to eat up alot of resources on your server. While it might work create for a few people, it's not going to scale well. Your server might max out anywhere between 10-100 users (which is rather low).

One fix is to increase the time between each server poll, but this is only a linear fix and will degrade the experience of the users.

A better solution might be to use a comet approach. This is hard (if not impossible) to do purely with PHP, so you will need to deal with some external API to handle the long http requests.

于 2010-08-16T03:54:17.390 回答