Reputation: 133
I have a chat room, running in the console. The server supports multiple clients through thread use. When I run it, the server then the client, the client connects fine. I send a message through the client program, "hello", and the client prints out the message, indicating that the server got the message (this is what the server is meant to do). But when I run another client at the same time, I send a message on one client but the message is not printed on the other client. Why would that be the case? There are no errors, and the clients connect fine.
Regards Bl-H
I will post code upon request.
Ok this is the code for server sending message to client (this is the method from the thread class):
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);
}
}
}
Upvotes: 0
Views: 1624
Reputation: 21
You can use hashmap for putting all of your clients there 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();
}
}
By the way, n here is private static final String n = "\r\n";
Upvotes: 0
Reputation: 1106
On the server-side, when you're creating one Thread per client, you need to have a HandleClient class (which implements the Runnable interface) in which you have to get back the PrintWriter (of each client). Each PrintWriter symbolize the connection between your server and one client. You just have to create an ArrayList of PrintWriter
(which will represents your clients), and then do a loop on it and do something like that (don't exactly remember)
public void transferMessagetoAll(PrintWriter sender)
{
for(i=0;i<PrintWriterArray.size();i++)
{
if(PrintWriterArray.get(i) != sender)
{
PrintWriterArray.get(i).println("something");
}
}
}
Also, you should set the client "sender" PrintWriter into parameter to the transferMessagetoAll
() method, so you can transfer message from the sender to all the other except him.
I already released this kind of java software (with UI). I can send you my personal source code (no matter, it was a scholar project) when I'll be back from work.
Upvotes: 1