【发布时间】:2012-05-29 05:55:29
【问题描述】:
我正在用 java 创建一个多线程聊天服务器。 当用户 u1 登录并向用户 u2 发送消息时,如果用户 u2 未连接,则将消息发送到服务器并放入待处理消息的 ArrayList 中。当用户 u2 连接时,他会收到来自服务器的消息,并将消息作为回执发送给用户 u1。
这是我的代码:
if (pendingmsgs.size()>0) {
for(Iterator<String> itpendingmsgs = pendingmsgs.iterator(); itpendingmsgs.hasNext();) {
//....parsing of the message to get the recipient, sender and text
String pendingmsg = itpendingmsgs.next();
if (protocol.author != null && protocol.author.equals(recipient)) {
response+=msg;
protocol.sendMsg(sender, "Msg "+text+" sent to "+recipient);
itpendingmsgs.remove();
}
}
}
out.write(response.getBytes(), 0, response.length());
这是 ServerProtocol sendMsg() 方法:
private boolean sendMsg(String recip, String msg) throws IOException {
if (nicks.containsKey(recip)) { //if the recipient is logged in
ClientConnection c = nick.get(recipient); //get the client connection
c.sendMsg(msg); //sends the message
return true;
} else {
/* if the recipient is not logged in I save the message in the pending messages list */
pendingmsgs.add("From: "+nick+" to: "+recip+" text: "+msg);
return false;
}
}
这是 ClientConnection sendMsg() 方法:
public void sendMsg(String msg) throws IOException {
out.write(msg.getBytes(), 0, msg.length());
}
其中 out 是一个 OutputStream。
当用户 u1 登录时,向未登录的用户 u2 发送消息,然后用户 u1 离开,当用户 u2 登录时,他没有收到消息,我收到此异常:
Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at ChatServer$ClientConnection.run(ChatServer.java:400)
at java.lang.Thread.run(Unknown Source)
第 400 行是
itpendingmsgs.remove();
我尝试过使用 CopyOnWriteArrayList,但它仍然不起作用。
【问题讨论】:
-
对不起,第 400 行是它pendingmsgs.remove();
标签: java