我有一个聊天室,在控制台中运行。服务器通过线程使用支持多个客户端。当我运行它时,服务器然后是客户端,客户端连接正常。我通过客户端程序发送一条消息“hello”,客户端打印出该消息,表明服务器收到了消息(这就是服务器应该做的事情)。但是,当我同时运行另一个客户端时,我在一个客户端上发送一条消息,但该消息不会打印在另一个客户端上。为什么会这样呢?没有错误,客户端连接正常。
问候 BL-H
我将根据要求发布代码。
好的,这是服务器向客户端发送消息的代码(这是线程类中的方法):
public void run() {
PrintStream output = null;
BufferedReader input = null;
String message;
try {
//i/o for clients:
output = new PrintStream(server.getOutputStream());
input = new BufferedReader(new InputStreamReader(server.getInputStream()));
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
while(true) {
try {
message = input.readLine();
output.println(message);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
}
}
最佳答案
在服务器端,当您为每个客户端创建一个线程时,您需要有一个 HandleClient 类(它实现 Runnable 接口(interface)),您必须在其中获取(每个客户端的)PrintWriter。每个 PrintWriter 都象征着您的服务器和一个客户端之间的连接。您只需创建一个 PrintWriter
的 ArrayList(它将代表您的客户端),然后对其进行循环并执行类似的操作(不太记得了)
public void transferMessagetoAll(PrintWriter sender)
{
for(i=0;i<PrintWriterArray.size();i++)
{
if(PrintWriterArray.get(i) != sender)
{
PrintWriterArray.get(i).println("something");
}
}
}
此外,您应该将客户端“发送者”PrintWriter 设置为 transferMessagetoAll
() 方法的参数,这样您就可以将消息从发送者传输到除他之外的所有其他人。
我已经发布了这种java软件(带UI)。当我下类回来时,我可以向您发送我的个人源代码(不管怎样,这是一个学者项目)。
关于java聊天室无法从多个客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11028479/