dpnvrt3119 2014-04-16 17:28
浏览 124

长轮询服务器循环

I am trying to make a notification system of incoming messages. For examlpe user stays on the page and he recieves in a block that he has 2 unread messages.

My client code:

(function getmess(){
var id = '<?=$MY_ID;?>';
    $.ajax({
      url:"notif.php",
      data:{"id":id,},
      type:"GET",
      success: function(result){
        $("#count").html(result);
      }, dataType: "json",
      complete: getmess,
      timeout: 10000});
})();

My server code:

<?php
    $mysqli = new mysqli('localhost', 'root', '', 'lc');
    if (mysqli_connect_errno()) { 
        printf("error: %s
", mysqli_connect_error()); 
        exit; 
    }  

$MY_ID = $_POST['id'];

while (true) {
$result = $mysqli->query("SELECT COUNT(*) FROM messages WHERE user_get='$MY_ID' AND status='0' ");
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_array($result)) {
echo $row[0]."";
}
exit;
}
sleep(5);
}

Everything works, but I have the problem that ajax requests are sent every 1 second and the lengh of these request is 1 second, and they overload the server.

I want to wait for a response from the server for at least 10 seconds in the case of a successful response to immediately send a new request, as well if the server does not respond within 10 seconds, ie in the database there is no change, then send a new query length of 10 seconds.

I think that is something wrong with server (may be sever loop), but i dont know how to improve this.

  • 写回答

2条回答 默认 最新

  • duanqiao9541 2014-04-16 17:32
    关注

    I'm sorry to say this is not going to work because for every user, your server has an open thread. That's going to get real heavy really fast.

    It would be better to just poll the server ie. once per minute, and then have the server handle that request only once and not keep it open.

    It is possible though, just not with PHP. Check out http://cometd.org/ for example.

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制