2015-10-11 150 views
3

我正在建立人與人聊天,並且希望人員A的頁面刷新,並在人員B發送時從人員B加載新消息。當人B通過PHP發送消息時,如何向A發送消息/數據?我知道我可以通過Ajax檢查Person A的頁面,但不斷運行MySQL查詢會大大降低服務器的速度。有任何想法嗎?PHP/JQuery - 將數據從另一個客戶端發送到客戶端

編輯:使用服務器發送的事件,這是我的腳本代碼:

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

我知道你在想使用一個WebSocket的。我個人從來沒有嘗試過使用一個,我真的不知道它是如何工作的,但我知道這就是你將使用websocket的原因。 – Rasclatt

+0

你能給一些說明/信息作爲答案嗎? – k97513

+0

我真的不能。以下是我希望有一天可以嘗試的鏈接,對您而言可能有價值,也可能沒有價值:https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications – Rasclatt

回答

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 ?>"; 
    } 
} 
相關問題