我正在尝试使用 webcocket 编写聊天,对于离线用户,我使用了 java Queue,如果用户离线,我将消息保存在队列中,当用户上线时,我检查队列是否为空,如果不是,使用循环我删除来自队列的每条消息。问题是即使所有消息都在队列中,它只是向用户发送最后一条消息,这是我的 onOpen 方法:
@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();
}
}
}
}}
有谁知道问题出在哪里?