【问题标题】:Long Polling Becoming a Ghost长轮询成为幽灵
【发布时间】:2012-02-03 01:32:57
【问题描述】:

我正在创建一个通知系统,该系统会立即检查在线用户是否有任何新通知。

到目前为止,这是我的脚本:

//...include(myscripts.php)...

function notificationsCount($id)
{
    if(is_numeric($id) && !empty($id) && $id>0) return mysql_result(mysql_query("SELECT COUNT(*) FROM notifications WHERE unRead='1' AND userID = '$id'"),0);
}

if($_GET['getNotificiationCount'] && $_GET[userID])
{
$current = notificationsCount($_SESSION['userID']);
$count = 0;
while($count<20 && !connection_aborted()){
    $c = notificationsCount($_SESSION['userID']);
    if($c!=$current && $c!=0)
        exit($c);
    
    $count++;
    sleep(1);
}
exit("0");
}

客户端:

var checkNotify;
$(window).unload(function () { checkNotify.abort(); } );

//Nav Notifications
function checkNotifications()
{
    checkNotify = $.ajax({
        url: "/notifications.php?getNotificiationCount=true&userID=<?=$_SESSION[userID]?>",
        timeout: "30000",
        cache: false,
        success : function(data, textStatus, XMLHttpRequest) {
                    if(data!=0) {
                    $("#nav_notification_bubble").removeClass("displayoff");
                    $("#notification_count").html(data); }
                    checkNotifications();
                },
        error: function() {}
    });

}
checkNotifications();

这可行,但是如果我离开页面,网络服务器将不会响应(在我的客户端),直到“notifications.php”脚本完成。

如果客户端离开页面,我该怎么做才能杀死脚本?

我的 Web 服务器是否打开了 Apache Gzip - 会等待缓冲区完成吗?

【问题讨论】:

  • JavaScript 需要异步编写。 checkNotify 是试图被覆盖而不是创建新实例的单个 var。

标签: php javascript jquery apache long-polling


【解决方案1】:

Apache 有一些特性支持 COMET 我听说了。你可以去。

或者另一种选择是在 Glassfish 应用服务器中使用 Grizzly 框架。

或者另一种解决方案是使用 Lightstreamer。你猜怎么了?如果您编写自定义代码,

它们可能在本地系统中运行良好,但实时可能会给服务器带来太多麻烦。

所以我想更好的选择是找到已经构建了很长时间的东西

研究工作。因为这更像是“黑客”而不是“技术”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 2018-06-16
    • 2011-07-09
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多