我正在尝试使用 EventSource 来创建一个 1 对 1 的实时连接聊天。我已经设置了我的事件源,并且从开发人员工具告诉我的内容来看,它是打开的并且可以工作,但是没有从 PHP 文件中显示响应数据。
PHP:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
session_start(); // Starting Session
include 'dbconnect.php';
include 'Session.php';
$messageuserid = $_GET['messageuserid'];
$RunSqlGM = "SELECT * FROM messages WHERE (SUsername = '$Session_Username' AND RUsername = '$messageuserid') OR (SUsername = '$messageuserid' AND RUsername = '$Session_Username')";
$getmessagethread = mysqli_query($con,$RunSqlGM)or die(mysqli_error());
while($MessageRows = mysqli_fetch_array($getmessagethread)) {
$MSUsername = $MessageRows['SUsername'];
$MRUsername = $MessageRows['RUsername'];
$MSender = $MessageRows['Sender'];
$MessageContent = $MessageRows['Message'];
$TimeStamp = date("g:ia \o\\n l jS F Y", strtotime($MessageRows["Time"]));
if ($MSender === $Session_Username) {
echo "<table class='messagebubbleright'>";
echo "<tr><th></th></tr>";
echo "<tr>";
echo "<td class='inforight'>$MSender<br>$TimeStamp</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='bubbleright'>$MessageContent</td>";
echo "</tr>";
echo "</table>";
flush();
} else {
echo "<table class='messagebubbleleft'>";
echo "<tr><th></th></tr>";
echo "<tr>";
echo "<td class='infoleft'>$MSender<br>$TimeStamp</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='bubbleleft'>$MessageContent</td>";
echo "</tr>";
echo "</table>";
flush();
}
}
mysqli_close($con); // Connection Closed
?>
调用事件源的js包含在该函数中,该函数通过单击按钮启动。
JS:
function GetMessages(GetMUserID) {
if (typeof(EventSource) !== "undefined") {
var source = new EventSource("db/getmessages.php?messageuserid=" + GetMUserID);
source.addEventListener("open", function() {
$("#readmessagearea").html("Getting server updates");
});
source.addEventListener("message", function(event) {
$("#readmessagearea").html(event.data);
});
} else {
$("#readmessagearea").html("Sorry, your browser does not support server-sent events...");
}
}
任何帮助或指导将不胜感激。我对 SSE 比较陌生,但据我所知,这应该可行。