且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用彗星长轮询将消息发送到服务器

更新时间:2023-01-17 10:42:32

是的,只需用完与服务器的第二个连接即可.这就是大多数框架所做的,包括iirc Bayeux协议.如果发现您确实需要第二个连接,则不必担心.

Yes, just use up the second connection to the server. This is what most frameworks do, including iirc the Bayeux protocol. If you find out you actually need that second connection, worry about it then.

这是我上面的链接中修改的一些长轮询代码:

Here's some long-polling code modified from my link above:

var userid = Math.ceil(1000000*Math.random()).toString(16).toUpperCase();
var startLongpoll = function() {
    $.ajax({
        type:"POST", async:true, cache:false, timeout:0, 
        data: {userid: userid},
        success: function(data){
            _outCallback(data);
            setTimeout( startLongpoll, 10 );
        },
        error: function(xhr, textStatus, errorThrown){
            _errCallback(textStatus+" ("+errorThrown+")");
            setTimeout( startLongpoll, 5000 );
        },
    });
};
setTimeout(startLongpoll,10);

Moishe在队列中谈论的是js不保证xhrs会按照您分派它们的顺序被接收.消息不会丢失(或者至少没有经过我的测试),这不是一个特定的长期轮询问题,而是每当您使用xhr发送时都要考虑的问题.

What Moishe was talking about with the queue is that js doesn't guarantee that xhrs will be received in the order that you dispatched them. The messages won't be lost (or at least they haven't been in my tests), and this isn't a specific long-polling issue, but something to consider whenever you use xhr to send.

所以这是队列代码:

var queue = [];
var busy = false;
this.send = function(msg) {
    queue[queue.length] = msg;
    if (busy) return;
    busy=true;
    var s = function() {
        var m = queue.shift();
        $.ajax({
            type:"POST", async:true, cache:false, timeout: 5000,
            data: {userid:userid, msg:m},
            error: function(xhr, textStatus, errorThrown){
                _errCallback(textStatus + " (" + errorThrown + ")");
                if (queue.length>0) s(); else busy = false;
            },
            success: function(){
                if (queue.length>0) s(); else busy = false;
            }
        });
    }
    s();
};

有两件事要注意.首先,如果您要发送许多消息并且队列已满,则会有相当大的滞后.***找到一种每次发送整个队列的方法,而不是逐个发送.一种方法是将消息转换为JSON数组,然后在服务器上解码.

Two things to note. First, there's a fair bit of lag if you're sending many messages and the queue is filling up. It's better to find a way to send the entire queue each time, rather than piece by piece. One way to do this is to convert the messages into a JSON array, and decode on the server.

第二,如果发送消息时出错,则说明您丢失了消息.需要一些代码,要么将失败的消息推回队列,要么在成功之前不将其删除.

Second, if there's an error sending the message, then you've lost the message. There needs to be a bit of code that will either push the failed message back onto the queue, or not remove it until there's success.