聊天应用程序用户如何再次联机时,如何获得脱机时发送给他们的消息

时间:2019-01-29 22:12:05

标签: android node.js redis socket.io android-room

我正在开发一个Android聊天应用程序,使用Node Js和Redis存储消息和用户信息。我正在使用套接字io进行通信,并使用Room将消息存储在本地数据库中。当用户离线时,我希望他们再次在线时收到他们的消息。我的问题是,当用户A离线时,用户B向他发送许多消息(例如5条消息),而当用户A再次在线时,他仅收到第一条消息,而最后一条消息却收到4次。这就是我正在做的事情,一旦用户收到一条消息,我会将Redis中的消息状态从“已发送”更新为“已发送”。在用户脱机的情况下,我将其消息存储在Redis中,其状态为消息“已发送”,并且再次联机时,我检查例如从用户B收到的消息,如果其状态为“已发送”,则我进行传递它发送给用户,然后将其更新为“已交付”,如下面的代码所示:

      //On this event, we update the socket ID of the sender in Redis so they can 
receive private messages from their contacts
socket.on('sender', (sender, destinat) =>{
tempId = socket.id;
senderId = sender;
users[sender] = sender;
users [destinat] = destinat;

//We also update the user status: online
client.hset(senderId, 'lastSeen', 'Now', function(reply){
           console.log( senderId + reply);
     });

//Stocking to the user socket id 
client.hset(users[sender], 'tempId', tempId, function(){
           console.log("Welcome " + sender);
            console.log("Welcome " + tempId);
  });


 //Getting all the messages of the sender from users

 //If the sender has any messages that hasn't received yet, they'll be sent 
  here
 //the id of each message is compsed of two parts: the phone number of the 
 receiver, and the id of  the message itself 
 (receiverPhoneNumber:idMessage)
  client.keys(users [sender] + ':*', function(err, results) {

      results.forEach(function(key) {


         client.hgetall(key, function(err, reply){

             if(err)
             console.log(err);
             else if(reply){

      //Compare the message status: if not sent, deliver it to receiver once online

                  if('Sent'.localeCompare(reply.status) == 0 && users 
[destinat].localeCompare(reply.fromUser)  == 0) {

                   io.to(tempId).emit('message', reply);


              }  

        }


    });


 });


 });

 });

从服务器接收到消息后,我使用Async将它们存储在Room Database中,然后将其显示给用户,如以下代码所示

这是AsyncTask类:

class AddMessage extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {


        //Creating a user account
        m = new Message();
        m.setContent( message );
        m.setTime( time );
        m.setUrl( url );
        m.setStatus( status );
        m.setFromUser( fromUser );
        m.setToUser( toUser );
        m.setUsername( receiver.getUsername() );
        //adding to database
        DatabaseClient.getInstance(getContext()).getAppDatabase()
                .messageDao()
                .insert(m);

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Toast.makeText( getContext(), "Added!", Toast.LENGTH_SHORT ).show();



    }
}

我检查了是否已正确从服务器收到消息到android应用程序(一旦将消息重新发送到服务器后再重新发送到服务器)。我相信问题与AsyncTask有关,但我想不通,非常感谢您的帮助,非常感谢。

 //When receving a message
    socket.on("message", new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject data = (JSONObject) args[0];
                        try {
                            //extract data from fired event


                            idMessage = data.getString( "idMessage" );
                            message = data.getString("message");
                            fromUser = data.getString( "fromUser" );
                            toUser = data.getString( "toUser" );
                            time = data.getString( "time" );
                            status = data.getString( "status" );
                            url = data.getString( "url" );             
                             //Here we call asyncTask to Add it to Database
                            addMessage = new AddMessage();
                            addMessage.execute(  );

                            //We emit this event to update the status of 
                            the message to delivered
                            socket.emit( "sent", idMessage, userID );


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
            }

        }
    });

1 个答案:

答案 0 :(得分:0)

我通过切换到RxJava而不是AsyncTask解决了这个问题。该问题与AsyncTask有关,因为它有时会影响数据链,而this link中提到的RxJava则不是这样:“ AsyncTasks的另一个问题是如果您一次运行多个。您无法保证它们将以什么顺序完成,从而导致检查所有任务何时完成的逻辑复杂,更糟糕的是假设一个任务要比另一个任务先完成,直到遇到使第一次呼叫变慢的极端情况为止,这会使它们以错误的顺序完成并产生不良结果。”