PHP / JQuery - 从另一个客户端向客户端发送数据

时间:2015-10-11 23:36:28

标签: php jquery mysql ajax chat

我正在建立一个人与人聊天,并希望人员A页面刷新,当人员B发送他们时从人员B加载新消息。当Person B通过PHP发送消息时,如何向Person A发送消息/数据?我知道我可以通过Ajax查看Person A的页面,但是不断运行MySQL查询会大大降低服务器的速度。有什么想法吗?

编辑:使用服务器已发送事件,这是我的脚本代码:

if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("update.php?user=<? echo $recip ?>");
    source.onmessage = function(event) {
    document.write(event.data);
    if (event.data=="yes"){
    window.location.href="/chat?with=<? echo $recip ?>";
    }
    };
} else {
    document.getElementById('info-text').innerHTML="Hmm... looks like your browser doesn't support auto updating. Please refresh the page to check for new messages." //'
}

这是我的PHP代码:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$user=$_GET['user'];
$sql=mysql_query("SELECT * FROM chatmsg WHERE sender='$myusername' AND receiver='$recip' OR sender='$recip' AND receiver='$myusername'");
$newrows=mysql_num_rows($sql);
if ($newrows!=$_SESSION['chat'.$user]) {
echo "data: yes";
flush();
}
else {
echo "data: no";
flush();

问题是,当MySQL中出现新行时,什么也没发生。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,每个人。我仍然使用Server Sent Events,但进行了一些更改并发现了错误。这是最终的工作代码:

PHP:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); 
header("Access-Control-Allow-Origin: *");
$user=$_GET['user'];
$sql=mysql_query("SELECT * FROM chatmsg WHERE sender='$myusername' AND receiver='$user' OR sender='$user' AND receiver='$myusername'");
$newrows=mysql_num_rows($sql);
if ($newrows!==$_SESSION['chat'.$user]) {
  $msg="yes";
}
else {
  $msg="no";
}  
echo "data: {$msg}\n\n";
flush();
sleep(10);

(睡眠是为了节省服务器资源)。

JS:

var source = new EventSource('update.php?user=<? echo $recip ?>');
source.onmessage = function(e) {
  if (e.data=="yes") {
    window.location.href="viewchat.php?viewer=<? echo $viewer ?>&recip=<? echo $recip ?>";
  }
}