我正在尝试构建一个多用户聊天系统,其中数据保存在数据库中并根据请求提取。下面的一段代码只是一个例子,我知道它有很多很好的 SQL 注入,一旦整个事情运行良好,我会改变它们。加上将 php 服务器代码保存在同一个文件中只是为了将代码保持在一个位置,我将在这里解释的问题仍然存在,当服务器代码位于不同的 php 文件中时。
该代码运行良好,但问题是我的数据库在一段时间后停止响应。如果有更多用户同时聊天(此脚本的多个实例),那么数据库很快就会停止响应一段时间,并在一段时间后再次开始响应。请建议我哪里出错了。
<?php
if($_POST){
$db=mysqli_connect("localhost","***","****","****");
if ( isset($_POST['update']) ){
$q = 0;
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while (1){
sleep(3);
$mresult = mysqli_query($db,"SELECT * FROM tblchat WHERE msg_datetime > $lasttime");
$wresult = mysqli_query($db,"SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if (mysqli_num_rows($mresult)){ $msgs = array(); while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; } mysqli_free_result($mresult); echo json_encode(array("writers"=>$writers,"msgs"=>$msgs)); flush(); break; }
if (mysqli_num_rows($wresult)){ $writers = array(); while ($row = mysqli_fetch_object( $wresult )) { $writers[] = $row; } mysqli_free_result($wresult); echo json_encode(array("writers"=>$writers,"msgs"=>$msgs)); flush(); break; }
++$q;
if ($q>15){ break; }
}
}elseif ( isset($_POST['save']) ){
$msg = isset($_POST['msg']) ? $_POST['msg'] : '';
if ($msg != ''){
$from = $_POST["from"];
$to = $_POST["to"];
mysqli_query($db,"INSERT INTO tblchat VALUES('".$to."','".$from."','".$msg."','".time()."')");
echo json_encode(array("success"=>"1"));
flush();
}
}
mysqli_close($db);
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>testing comet</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p>
<input type="text" name="word" id="word" value="" />
<input type="button" name="send" value="Send" id="mybutton"/>
</p>
<div id="content"></div>
<script type="text/javascript">
var lastime = 0;
$("#mybutton").click(function(){
$.post(location.href, {save:"1",from:"1",to:"5",msg:$("#word").val()}, function(data){
console.log(data);
$("#word").val("");
}, "json");
});
$(document).ready( function(){ update(); } );
function update(){
console.log("update called");
$.ajax({ type: "POST", url: location.href, data: {update:"1",timestamp:lastime}, success: function(data1){
console.log(data1);
lastime = handleDATA(data1.msgs);
}, dataType: "json", complete: update, timeout: 60000 });
}
function handleDATA (data){
for(i=0;i<data.length;i++){
$("#content").append(data[i].msg_from +": "+ data[i].msg+"</br>");
}
return data[data.length-1].msg_datetime;
}
</script>
</body>
</html>