import java.io.*;
import java.net.*;
import java.util.*;
public class BroadcastClientHandler extends Thread {
protected Socket incoming;
protected int id;
protected BufferedReader in;
protected PrintWriter out;
public BroadcastClientHandler(Socket incoming, int id){
this.incoming = incoming;
this.id = id;
try{
in = new BufferedReader( new InputStreamReader( incoming.getInputStream()));
out = new PrintWriter( new OutputStreamWriter( incoming.getOutputStream()));
} catch(Exception e){}
}
public synchronized void sendMessage(String msg){
if(out != null) {
out.println(msg);
out.write(0);
out.flush();
}
}
public void run(){
if(in != null && out != null){
sendMessage("<hello id=\""+id+"\"/>");
try{
while(true){
String str = in.readLine();
if(str==null){
}else {
//sendMessage(str); send to self?
if(str.trim().equals("")){
System.out.println("Client "+id+" has disconnected");
break;
}
else{
Iterator iter = BroadcastEchoServer.activeClients.iterator();
while(iter.hasNext()){
BroadcastClientHandler t =
(BroadcastClientHandler)iter.next();
if(t!=this) t.sendMessage(str);
}
}
}
}
incoming.close();
BroadcastEchoServer.activeClients.remove(this);
} catch(IOException e){ System.out.println("Client "+id+" Leaving while loop"); }
}
}
}