PollingPattern正在失去一些数据

时间:2015-08-08 14:27:38

标签: jquery ruby-on-rails

我们正在构建一个能够与用户直接聊天的消息系统。由于我们使用的是Rails3,并且4月的升级即将到来,我们将进行轮询而不是流式传输。

我们遇到了问题,可能是由设计模式引起的。

function OurChat() {
    this.timestamp = null
    var self = this
    this.init = function() {
        self.timestamp = (new Date().getTime()).toString().substr(0, 10) //rails conform

然后我们启用轮询,频率为5000毫秒

this.polling = function() {

    $.getJSON("/chat.json?t=" + self.timestamp, function(data) {
        self.set_timestamp()

        self.update_friends(data.friends)
        self.update_messages(data.messages)

        window.setTimeout(function() {
            self.polling();
        }, self.frequency);
    });        
}

如果我们写一条消息,我们会将请求发送到服务器并显示带有“.temporary”类的消息

当我们轮询时,我们删除带有临时类的消息,并将服务器响应的消息添加到我们的消息列表中。 这里问题就出现了。

示例

last_polling_timestamp is **1000**
[...4.5 seconds are gone...]
 -> user sends a message -> request takes whatever it takes
[..5seconds are gone..]
 -> poling is looking for messages > timestamp **1000** 
    ->  _blank result_
[..little bit later..]
 -> message is created by server, timestamp **1001**
[..5seconds are later..]
 -> poling is looking for messages > timestamp **1005** 
    ->  _blank result_

我们该如何解决这个问题? 我最好的想法是发回每条消息的ID,将ID保存在.message [data-id]。然后通过轮询总是过去10秒(这样每个请求应该已经存在)。检查所有消息,看看它是否已经在我的domtree中。如果不是 - >插入它(在正确的oder中)。 这是一种更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我们现在禁用输入字段,只要请求未完成。

相关问题