2012-10-18 47 views
3

因此,我正在实现一个应用程序,要求将消息实时发送到浏览器。目前这工作正常。当我收到一条消息时,我会看到一个类似于时钟示例的非类型化Actor。Playframework彗星socket捕获客户端断开连接

虽然我的问题是我希望能够重新连接彗星套接字断开连接时的网页。目前在铬彗星插座中,加载图标不断旋转。有没有一种方法可以捕获iframe/comet插槽的断开连接信息?或者有什么我可以在javascript/jquery中进行轮询?那么我可以重新加载页面?

回答

0

如果你想重新连接“网页”(换句话说,让你的浏览器发送另一个请求到服务器,使用window.location.reload()或其他方法),标准play.libs.Comet.onDisconnected处理程序对你没用 - 它的域是服务器端,而不是客户端。

为了让您的客户端管理本身可能停电,您可能需要实施'心跳'方案。自上一条消息以来,过多的时间过去后,客户端应用程序将ping您的服务器。一种可能的方式做到这一点:

var CometProcessor = { 
    processMessage:   function(message) { 
    console.log(message); 
    }, 
    handleHeartbeatTimeout: function() { 
    alert('Heartbeat process timeout'); 
    }, 
    handleHeartbeatError: function() { 
    alert('Heartbeat process error'); 
    }, 

    timeoutPeriod: 10000,  // in milliseconds 
    timeoutId:  0,   // will contain an ID of the current 'checking' timeout 
    checkHandler: null,  // will contain a link to XHR object 

    checkBeat: function() { 
    // storing the reference to created XHR object: 
    this.checkHandler = $.ajax({ 
     url:  your_server_url, 
     // set it to the URL of ping script, that will respond instantly 

     timeout:  1000, 
     // this is configurable, but obviously it makes little sense setting this param 
     // higher than `timeoutPeriod` 

     success:  $.proxy(function() { 
     // so this particular heartbeat request check went through ok, 
     // but the next may not be so lucky: we need to schedule another check 
     this.timeoutId = window.setTimeout(
      $.proxy(this.checkBeat, this), this.timeoutPeriod); 
     }, this), 

     error:  $.proxy(function(x, t) { 
     if (t === 'timeout') { 
      this.handleHeartbeatTimeout(); 
     } 
     else { 
      this.handleHeartbeatError(); 
     } 
     }, this) 
    }); 
    }, 

    message: function(message) { 
    // when we receive a message, link is obviously functioning, 
    // so we need to stop all the checking procedures 
    if (this.checkHandler) { 
     this.checkHandler.abort(); 
     window.clearTimeout(this.timeoutId); 
     this.checkHandler = null; 
    } 
    processMessage(message); // this is where the actual processing takes place 

    // when we done with processing, we need to setup the heartbeat again: 
    this.timeoutId = window.setTimeout(
     $.proxy(this.checkBeat, this), this.timeoutPeriod); 
    } 
}; 

利用在服务器端的这个对象是很容易:你只需要更换一个类似于在this example行...

Ok.stream(events &> Comet(callback = "parent.cometMessage")) 

.. 。with:

Ok.stream(events &> Comet(callback = "parent.CometProcessor.message"))