How to send offline user messages after going online in java websocket?

I am trying to write a chat using webcocket, for offline users. I used java Queue if user is disconnected. I store messages in a queue and when the user connects to the network, I check if the Queue is empty, and if not, using a loop I remove all messages from the queue. The problem is that it just sends the last message to the user even if all messages are in the queue, here is my onOpen method:

@ServerEndpoint(value = "/chat/{room}/{user}", encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class)
 public class ChatEndpoint {


private final Logger log = Logger.getLogger(getClass().getName());
private static final Map<String, Queue<ChatMessage>> userMessageBuffer = new HashMap<>();

@OnOpen
public void open(final Session session,
        @PathParam("room") final String room,
        @PathParam("user") final String userId) {

    log.info("session openend and bound to room: " + room);
    // session.getUserProperties().put("room", room);
    session.getUserProperties().put("user", userId);

    Queue<ChatMessage> userMsgs = userMessageBuffer.get(userId);
    ChatMessage sendChat = new ChatMessage();

    if (userMsgs != null && !userMsgs.isEmpty()) {

        for (int i = 0; i < userMsgs.size(); i++) {

            sendChat = userMsgs.remove();
            System.out.println("size!!!!!! " + sendChat.getMessage());
            try {

                    session.getBasicRemote().sendObject(sendChat);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (EncodeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

}}

      

Does anyone know where the problem is?

+3


source to share


1 answer


I haven't tested the complete code, but of course

      for (int i = 0; i < userMsgs.size(); i++)

      

is your problem. Because you are using i++

and checking userMsgs.size()

as a condition in a for loop. So you increase i

by 1

and decrease the size userMsgs

by 1, effectively you will only be able to access half of the items in the queue.

let's say you have 8 items in the queue, initially (imagine this as Admiral General Aladeen

explaining about a round shaped rocket)



               i=0 and userMsgs.size()=8
               i=1 and userMsgs.size()=7
               i=2 and userMsgs.size()=6
               i=3 and userMsgs.size()=5
               i=4 and userMsgs.size()=4 // comes out of loop.

      

you should use a while loop instead,

  while(!userMsgs.isEmpty()){
   .....
  }

      

You said that you can only send the last message to the user, perhaps it is because you only have 2 messages in the queue. I know this is rare, but it should be according to your code.

+4


source







All Articles