I am trying to write a chat using webcocket, for offline users I have used java Queue, If user is offline I keep messages in a Queue and when user gets online I check if Queue is empty and if it's not, using a loop i remove each messages from Queue. The problem is it just sends last message to user even though all messages are in 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 any one knows where is the problem?
I did not check the complete code, but certainly
for (int i = 0; i < userMsgs.size(); i++)
is your problem. Because you are using i++
and checking userMsgs.size()
as a condition in for loop. So you are increasing i
by 1
and decreasing userMsgs
size by 1, effectively you will be able access only half of the elements in the queue.
say you have 8 elements in the queue, initially (Imagine this like Admiral General Aladeen
explaining about round shaped missile)
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 you are able to send only last message to the user, may be that is because you have only 2 messages in the queue. I know it's rare but that should be the case according your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.