为什么php sleep()暂停所有脚本的执行?

问题描述 投票:2回答:2

我正在尝试在php中实现简单的longpolling,我的服务器代码如下:

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查询相同,它可以正确返回所有内容。

Edit2:

除了最长执行时间,我没有收到任何错误。

php sleep long-polling
2个回答
0
投票

尝试这个,让我只知道一个例子,在我称呼它的同时看一行>>>删除它。因为在您的while循环中未评论,所以do和$array作为php函数运行

您的查询中没有""

$sql = SELECT * from table;


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);


this one >>>>>> 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);
}

0
投票

查看您的代码:

while(true){  // do this FOREVER unless we break the loop
   $sql = SELECT * from table;    // I assume we always get all rows?
   $result = mysqli_query($conn, $sql);
   $array = [];

   while ($row = $result->fetch_array()) {
        // Do stuff
        $array[] = $row;
   }
   // now array has all rows

   $jsonRes = json_encode($array);

   if (strcmp($jsonRes, $_SESSION["lastResult"]) == 0) {
        echo $jsonRes;
        $_SESSION["lastResult"] = $jsonRes;
        exit();
    }
    // so just sleep 5 seconds and do it all over again
    sleep(5);
}

在表中具有datetime列会不会更容易,并且如果一次select返回的更新时间的行晚于该事物上次运行的时间,那么选择*并返回?没有真正的循环吗?

© www.soinside.com 2019 - 2024. All rights reserved.