【发布时间】:2014-03-22 23:37:27
【问题描述】:
static ArrayList<Client> clients = new ArrayList<Client>();
while (true)
{
Socket s = server.accept();
System.out.println("Client connected from " + s.getLocalAddress().getHostName());
Thread t = new Thread(new Client(s));
t.start();
}
简单的前提是,在刚刚创建的 Client 类中,我将添加到位于主服务器类(上图)中的“Client”的静态 ArrayList,即
clients.add(Client.this);
然后我只是每隔 10 秒,将当前在线用户作为一个对象发送给当前在 ArrayList 中的所有客户端(全局消息有效)
for(int i =0; i < clients.size(); i++)
{
System.out.print("sending list");
clients.get(i).sendList();
}
现在,它确实正确添加了正确数量的客户端等。并且列表被正确收集,客户端每 10 秒愉快地收到此列表,直到,另一个客户端连接到服务器,一旦发生这种情况,第一个客户端停止接收列表,新的客户端取代它,获取所有“已接收列表”通知。这是怎么回事?
编辑:sendList() 代码
public void sendList()
{
try
{
ChatListObject list = new ChatListObject();
list.setList(helper.getOnlineUsers());
out.writeObject(list);
out.flush();
}
catch (IOException iOException)
{
System.out.println(iOException);
}
}
添加客户端的尝试:
Client client = new Client(s);
Thread t = new Thread(client);
t.start();
clients.add(client);
和
clients.add(this);
在客户端本身
【问题讨论】:
-
如何在客户端初始化“out”?它是如何声明的?
-
在初始化'Client' in = new ObjectInputStream(socket.getInputStream()); out = new ObjectOutputStream(socket.getOutputStream());它成功地以这种方式发送消息,只是简单地发送到最后一个连接
-
请复制“out”的实际声明,我猜它是静态的,因此在类的实例之间共享。这会给出你描述的症状。
-
^ BINGO BINGO 我们赢了!谢谢!自己永远不会发现它。将其发布为我可以接受的答案?
标签: java client-server chat