我有一个聊天室,在控制台中运行。服务器通过线程使用支持多个客户端。当我运行它,服务器然后客户端,客户端连接正常。我通过客户端程序“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);
}
}
}
答案 0 :(得分:1)
在服务器端,当您为每个客户端创建一个Thread时,您需要一个HandleClient类(实现Runnable接口),您必须在其中取回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");
}
}
}
此外,您应该将客户端“sender”PrintWriter设置为transferMessagetoAll
()方法的参数,这样您就可以将邮件从发件人传输到除他之外的所有其他邮件。
我已经发布了这种java软件(带有UI)。当我下班回来时,我可以将你的个人源代码(无论是学术项目)发给你。
答案 1 :(得分:0)
您可以使用hashmap将所有客户端放在HashMap<String, DataOutputStream> clients = new HashMap<String, DataOutputStream>();
public void run() {
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
while (true) {
dos.writeBytes("enter nick: ");
name = dis.readLine().trim();
if (chatters.get(name) != null) {
dos.writeBytes("nick has already been taken..."+n);
} else {
break;
}
}
chatters.put(name, dos);
sendToAll(name+" entered the chatroom... chat away"+n+n);
sendToAll(name+" exited the chatroom...");
chatters.remove(name);
dos.close();
dis.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
顺便说一下,这里的n是private static final String n = "\r\n";