Php 为什么我的聊天应用有时不接收消息?

Php 为什么我的聊天应用有时不接收消息?,php,mysql,laravel,polling,Php,Mysql,Laravel,Polling,我正在构建一个聊天web应用程序并使用间隔轮询。但是,有时客户端A发送的消息未被客户端B接收到。这种情况大约每发送20条消息中就有一条。客户端B上的页面刷新当然会导致消息被加载 这就是它的工作原理: 我正在使用会话存储客户端A上次轮询服务器的时间。当我进行下一次轮询时,服务器会检查数据库中时间(精确到微秒)大于上次轮询时间的消息。在使用最新消息执行任务后,服务器将在会话数据中保存当前时间,以用作下一次轮询的上次轮询时间 我知道会话会私自保存数据,因此其他用户无法访问。因此,两个客户端总是在不同的

我正在构建一个聊天web应用程序并使用间隔轮询。但是,有时客户端A发送的消息未被客户端B接收到。这种情况大约每发送20条消息中就有一条。客户端B上的页面刷新当然会导致消息被加载

这就是它的工作原理:

我正在使用会话存储客户端A上次轮询服务器的时间。当我进行下一次轮询时,服务器会检查数据库中时间(精确到微秒)大于上次轮询时间的消息。在使用最新消息执行任务后,服务器将在会话数据中保存当前时间,以用作下一次轮询的上次轮询时间

我知道会话会私自保存数据,因此其他用户无法访问。因此,两个客户端总是在不同的时间轮询同一台服务器

出了什么问题?我是否应该使用缓存作为替代,以便两个客户端同时轮询同一个服务器?另外,我正在使用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
        }
}

使用ID,而不是时间

我要赞扬他在上面的评论

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

经过一些调整后,似乎没有任何消息出错。我想问题是利用时间获取最新消息。

能否提供代码。我们看不到现在发生了什么。@dwhite.me提供了代码。您确定这些消息已发布到数据库吗?@dwhite.me绝对正确。正如我所说的,客户端B上的页面刷新会导致消息被加载。我最怀疑的是在这里用时间戳来查询。如果由于某种原因,甚至有1微秒的重叠,您可能会错过一条消息。也许您不需要记录时间,而可以记录最后检索到的ID(假设消息上的ID递增),然后轮询ID大于该ID的消息