我需要帮助做一个在线聊天。我已经创建了一个简单的在线聊天,其中一个用户可以与另一个用户通信,他们的对话被保存为一个json文件。json文件是我使用setInterval().在每2秒重新加载一次之后重新加载的文件。用户发送的消息通过使用ajax并通过php函数fopen和fwrite(追加)附加到json文件上。
我的问题是,在ajax上发送/发布的过程太慢了。用户看到他/她的消息被发送到聊天屏幕(Div)需要一段时间。我尝试在屏幕上追加消息,看起来好像已经发送了消息,但问题是,当setInterval重新加载聊天屏幕,而新附加的消息尚未保存到json文件中时,新发送的消息将不会包含在该重新加载中。
问题:
发布于 2011-12-13 03:51:52
有几点需要考虑:
关于长极(彗星)的->搜索
->为什么setInterval刷新屏幕,它应该只是添加来自服务器的新消息
->如果使用基于HTML5的浏览器,请检查Websockets和服务器附带事件。
->在服务器端使用DB操作,而不是文件操作。它还将提高可维护性,考虑1000个不同用户之间聊天的情况,很难维护这些文件。
->服务器应该发送新的增量消息,它不应该仅仅将整个会话再次发送到客户端以进行解析和重新加载。
发布于 2011-12-13 03:52:38
我是最近才这么做的,这是代码
index.php
<?php
session_start();
if(isset($_GET['logout'])) {
session_destroy();
header("Location: index.php"); //
}
if(isset($_POST['username'])) {
if(trim($_POST['username']) != "") {
$_SESSION['username'] = stripslashes(htmlspecialchars($_POST['username']));
header("Location: index.php"); //
} else {
header("Location: index.php"); //
}
}
?>
<!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" lang="zh-CN">
<head profile="http://gmpg.org/xfn/11">
<title>chating</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="jquery-1.5.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="jquery.corner.js"></script>
<script type="text/javascript">
$("#main,#login").corner("15px");
</script>
<![endif]-->
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
//$("#main,#login").corner();
$("#message").focus();
$("#logout").click(function() {
if(confirm("Are you sure to exit this chat?")) {
window.location = "index.php?logout=yes";
}
});
$("#btnsend").click(function() {
//$("#chathistory").append("<div>" + $("#message").val() + "</div>");
//alert($("#chathistory").html());
if($("#message").val() == "") {
alert("Please input something !");
return false;
}
$.post("ajax.php", {message: $("#message").val()});
$("#message").val("");
$("#message").focus();
return false;
});
$("#message").keydown(function(e) {
if (e.ctrlKey && e.keyCode == 13) {
$("#btnsend").click();
}
//alert(e.keyCode);
});
function loadChatHistory() {
var oldscrollHeight = $("#chathistory").attr("scrollHeight") - 20;
$.ajax({
url: "ajax.php?type=getmsg",
cache: false,
dataType: "xml",
success: function(xmlData) {
var htmlData = "";
$(xmlData).find("Msg").each(function() {
htmlData += '<div><span class="people">' + $(this).find("MsgFrom").text() + " " + $(this).find("MsgDateTime").text() + '</span><p class="content">' + $(this).find("Message").text() + '</p></div>'
});
$("#chathistory").html(htmlData);
var newscrollHeight = $("#chathistory").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chathistory").animate({ scrollTop: newscrollHeight }, 'normal');
}
}
});
}
setInterval (loadChatHistory, 2500);
});
//]]>
</script>
</head>
<body>
<?php
//print_r(var_dump($_SESSION));
?>
<?php
if(!isset($_SESSION['username'])) {
?>
<div id="login">
<form action="index.php" method="post">
<label for="username">UserName:</label>
<input type="text" id="username" name="username" class="corner2"/>
<input type="submit" id="btnlogin" name="btnlogin" class="corner2" value="Login"/>
</form>
</div>
<?php
} else {
?>
<div id="main">
<p id="welcome">Welcome, <strong><?php echo $_SESSION['username'] ?></strong></p>
<p id="logout"><a href="#">Exit Chat</a></p>
<div class="clear"></div>
<div id="chathistory" class="corner2">
</div><!-- #chathistory -->
<div id="userlist" class="corner2">
</div><!-- #userlist -->
<div id="chatarea" class="corner2">
<textarea id="message" class="corner2" rows="2" cols="2"></textarea>
</div><!-- #chatarea -->
<div id="send">
<input type="button" id="btnsend" value="Send!" class="corner2" />
</div>
<div class="clear"></div>
</div><!-- #main -->
<?php
}
?>
</body>
</html>ajax.php
<?php
session_start();
date_default_timezone_set("PRC");
if(isset($_SESSION["username"])) {
$dbh = new pdo("sqlite:./Message.DB");
if(isset($_GET["type"]))
{
if($_GET["type"] == "getmsg") {
$strXML = '<?xml version="1.0" encoding="utf-8" ?>';
$strXML .= "<Msgs>";
foreach($dbh->query("select * from (SELECT * FROM Message ORDER BY MsgID DESC limit 0,500) ORDER BY MsgID ASC") as $row) {
$strXML .= "<Msg>";
$strXML .= " <Message>" . stripslashes(htmlspecialchars($row[1])) . "</Message>";
$strXML .= " <MsgDateTime>" . $row[2] . "</MsgDateTime>";
$strXML .= " <MsgFrom>" . stripslashes(htmlspecialchars($row[3])) . "</MsgFrom>";
$strXML .= "</Msg>";
}
$strXML .= "</Msgs>";
echo $strXML;
}
} else {
$message = $_POST["message"];
$message = str_replace("'","''",$message);
$SQL = "INSERT INTO Message(Message, MsgDateTime, MsgFrom) VALUES('" . $message . "', '" . date("Y-m-d H:i:s") . "','" . str_replace("'","''",$_SESSION["username"]) . "')";
//echo $SQL;
$dbh->query($SQL);
}
}
?>style.css
* {
margin: 0;
padding: 0;
}
body {
font-family: LucidaGrande, Tahoma, Verdana, Arial, IPAPGothic, sans-serif;
font-size: 14px;
line-height: 1.5;
background-color: #EDE8E2;
}
#main ,#login {
width: 600px;
margin: 30px auto;
padding: 20px;
background-color: #A8B6D3;
-moz-box-shadow: 10px 10px 5px #888888;
-webkit-box-shadow: 10px 10px 5px #888888;
box-shadow: 10px 10px 5px #888888;
-moz-border-radius:15px;
border-radius:15px;
}
#login {
text-align:center;
}
#login input[type="text"] {
border:0;
padding:5px;
}
#login input[type="submit"] {
border:0;
border:2px solid #5D92D0;
background-color: #A8B6D3;
padding:2px;
font-family: LucidaGrande, Tahoma, Verdana, Arial, IPAPGothic, sans-serif;
font-size: 14px;
}
#welcome {
margin-bottom: 10px;
float:left;
}
#logout {
text-align:right;
font-weight:bold;
}
#chathistory {
background-color: #fff;
width: 450px;
height: 250px;
padding: 4px 10px;
float: left;
overflow: auto;
}
#chathistory span.people {
color:#008040;
margin-right:10px;
}
#chathistory p.content {
margin-left:20px;
}
#userlist {
background-color: #fff;
margin-left: 480px;
padding: 4px 10px;
width:100px;
height: 250px;
overflow: auto;
}
#userlist ol {
list-style-type: none;
}
#chatarea {
background-color: #fff;
margin-top:15px;
height:70px;
width:470px;
padding: 0;
float:left;
}
#message {
width: 460px;
height:62px;
resize: none;
border: 0;
padding: 4px 0 4px 10px;
font-family: LucidaGrande, Tahoma, Verdana, Arial, IPAPGothic, sans-serif;
font-size: 14px;
line-height: 1.4;
overflow:auto;
}
#btnsend {
width:120px;;
height:70px;
margin-left: 10px;
margin-top:15px;
border:2px solid #5D92D0;
background-color: #A8B6D3;
font-family: LucidaGrande, Tahoma, Verdana, Arial, IPAPGothic, sans-serif;
font-size: 28px;
font-weight:bold;
}
.corner2 {
-moz-border-radius:5px;
border-radius:5px;
}
.clear {
clear:both;
}PS,i= SQLite数据库
发布于 2011-12-13 04:11:04
您应该使用数据库而不是平面文件,因为如果尝试同时读取和写入文件可能会出现问题,并且每隔两秒钟解析整个json格式化的会话需要不必要的处理,我建议使用sqlite,因为它易于设置,不需要任何特殊的数据库服务器软件,然后只需进行查询,为上次刷新后发送的当前会话选择所有消息,您的查询将按照以下方式进行:
获取消息:
mysql_query("SELECT * FROM `chat` WHERE `id` == '".$id."' AND `timestamp` > '".$lastfetch."'");发送信息:
$timestamp = time();
mysql_query("INSERT INTO `chat` (`id`,`message`,`timestamp`) VALUES('".$convoid."', '".$message."', '".$timestamp."')");
echo $timestamp;然后将回显的时间戳保存到javascript中的一个变量中,然后将其作为$lastfetch发送给下一个ajax,这样您的查询将获得自上次检查以来的所有新消息。
https://stackoverflow.com/questions/8484057
复制相似问题