2014-07-17 40 views
-1

我正在構建聊天Web應用程序並使用間隔輪詢。但是,有時由客戶端B未收到由客戶端A 發送的消息。發生這種情況就像發送了20個消息中的一次那樣。客戶端B上的頁面刷新當然會導致消息被加載。爲什麼我的聊天應用程序有時不接收消息?

這是它如何工作的:

我使用會話來存儲時間客戶端最後一個輪詢服務器。當我進行下一次輪詢時,服務器會檢查數據庫中的時間(精確到微秒)時間大於上次輪詢時間的消息。在做了最新的消息之後,服務器會將當前時間保存在會話數據中,以用作下一輪即將進行的輪詢的最後一次輪詢時間。

我知道會話會私下保存數據,所以其他用戶無法訪問它。所以兩個客戶端總是在不同的時間輪詢同一臺服務器。

出了什麼問題?我應該使用緩存作爲替代方案,以便兩個客戶端同時輪詢同一臺服務器嗎? P.s.,我使用Apache服務器和MySQL數據庫。

這裏的投票代碼laravel:

public function index(){ 

     $currentPoll = round(microtime(true) * 1000);//calculate the current time in microseconds 

     //if the session variable doesn't exist, set the lastPoll variable to 0 
     if(!($lastPoll = Session::get('lastPoll'))){ 
       $lastPoll = 0; 
     } 

     $selectedMsgExists = Input::get('selectedMsgExists');//check whether messages exist in currently opened conversation 

     //check if conversation is opened or not 
     if(Input::has('selectedID')){ 
      $selectedID = Input::get('selectedID'); 
     } 
     else{ 
      $selectedID = false; 
     } 

     $loginuser = User::find(Auth::user()->id);//get the currently logged in user 
     if($selectedMsgExists=='false'&&$selectedID){ 
     //if messages has not been loaded but conversation exists, we take the first ten messages of the opened conversation. 

      $allMessages = $loginuser->messages()->select('users.name')->join('users',function($join){ 
       $join->on('users.id','=','messages.user_id'); 
      })->where('conv_id','LIKE',$selectedID)->orderBy('microseconds','desc')->take(10); 

      Session::put('lastPoll',$currentPoll);//save the session 
      return array(false,$allMessages->get()->reverse());//return the latest messages. False is to indicate that the data returned is NOT a conversation 
     } 
} 
+3

您能否提供代碼?我們現在看不到發生了什麼。 – ggdx

+0

@ dwhite.me代碼提供 – Mark

+0

您確定郵件正在發佈到數據庫嗎? – ggdx

回答

0

使用ID,沒有時間!

我在上面的評論中給judereid分。

Another thing to consider... I would be most suspicious of querying by a timestamp 
here. If for some reason there's even as much as a 1 microsecond overlap you could 
miss a message. Perhaps instead of logging the time you could log the last 
retrieved ID (assuming you have incrementing ids on the messages) and then poll 
for messages with ID greater than that – judereid 

經過一些調整後,似乎沒有任何消息不對。我想這個問題真的是用時間來獲取最新的消息。

相關問題