2012-10-18 78 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"))