这个聊天脚本有效吗?
我使用 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 循环对服务器更加友好?
i made a chat using php and ajax, and i am using a while loop to check the database for new messages.
this is the code that retrieves the message:
//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");
?>
now this works fine,the php file constantly checks to see if there are any new messages, the update function starts when the page is loaded and waits for the response.
but is it efficient? if i would use this on a website, im afraid it would stress the server too much, because of the while loop. does anyone know of a way, to make that while loop more server friendly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的预感是正确的。典型的服务器设置每秒可以响应 100-1000 个 PHP 请求,因此每个客户端每秒执行 10 个请求将消耗服务器上的大量资源。虽然它可能适合少数人创建,但它不会很好地扩展。您的服务器可能最多可容纳 10-100 个用户(这是相当低的)。
一种修复方法是增加每个服务器轮询之间的时间,但这只是线性修复,会降低用户的体验。
更好的解决方案可能是使用 comet 方法。纯粹使用 PHP 很难(如果不是不可能)做到这一点,因此您需要处理一些外部 API 来处理长 http 请求。
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.