just come into contact with real-time communication, I know that using websocket is more efficient, but I want to know the implementation process of polling, step by step
the timer setInterval for short polling has been implemented, but when the background enters the endless loop module during long polling, the php page of the entire website becomes unresponsive, such as refreshing the page and submitting messages. The specific code is as follows:
chat.php:
<div class="chat_content_input">
<div>
<textarea name="chat_input" class="chat_input"
style="width: 570px;height: 120px;margin: 5px;resize: none"></textarea>
</div>
<div style="text-align: right">
<button class="chat_post"></button>
</div>
</div>
chat.js:
//
var setting = {
type: "POST",
dataType: "html",
url: "./util/action.php?action=message_pull",
data: {uid_get: $("-sharpchat_content").attr("uid")},//uid
success: function (msg) {
if (msg.length > 0) {
$(".chat_content_list_table").append(msg);//
}
$.ajax(setting);//
}
};
$.ajax(setting);
The corresponding function in action.php:
function message_pull($conn)
{
session_start();
session_write_close();//session
$uid_post = $_SESSION["userinfo"][0]["id"];//uid
$uid_get = $_POST["uid_get"];//uid
$message_list = "";
//
while (true) {
//
foreach (select($conn, "message", "(uid_get=$uid_post AND uid_post=$uid_get AND read_flag<>1)") as $message) {
update($conn, "message", "read_flag=1", "id={$message["id"]}");//
$message_list .= "<tr class="content_list_post" style="text-align: right;font-size: 18px"><td>" . $message["content"] . "</td></tr><tr><td style="text-align: right;font-size: 8px">" . $message["post_time"] . "</td></tr>";
}
if (strlen($message_list) > 0) {
echo $message_list;//
break;//
}else
sleep(1);//1s
}
mysqli_close($conn);
}
after testing, I found that once the php background enters the while loop, it will be blocked. But I saw that many demo on the Internet wrote this, so I felt very confused. Thank you for your advice
.reference link: https://www.cnblogs.com/zhenb.