<分区>
我正在尝试在 php 中实现简单的长轮询,我的服务器代码是这样的:
if (!isset($_SESSION["lastResult"])) {
$_SESSION["lastResult"] = "";
}
while(true){
$sql = "SELECT * from table";
$result = mysqli_query($conn, $sql);
$array = [];
while ($row = $result->fetch_array()) {
do something and insert each element into $array;
}
$jsonRes = json_encode($array);
//if old array is different from the new one, that means information has been updated,
//so I need to echo new data to user.
if (strcmp($jsonRes, $_SESSION["lastResult"]) == 0) {
echo $jsonRes;
$_SESSION["lastResult"] = $jsonRes;
exit();
}
//If information hasn't changed, just sleep for 5 seconds and repeat next time.
sleep(5);
}
和客户端代码:
const waitForData = () => {
//this is just a js fetch function
getDataHTTP().then(res => {
this.setState({ itemsData: res });
waitForData ();
});
};
waitForData();
但是在我的网络选项卡中发生了什么,我看到我的 getData php 脚本应该“挂起”,但它永远挂起,另一件事是我无法真正编辑网页上的任何其他数据,因为出于某种原因,我假设是 sleep()
函数,我所有的 php 脚本都停止工作,并且永远处于“待定”状态。
提前致谢。
编辑:
仅作记录,$_SESSION 变量有效,所有数据都在其应有的位置。 SQL 查询也是如此,它会正确返回所有内容。
编辑2:
除了最大执行时间之外,我没有收到任何错误。