import java.net.*; 
import java.io.*; 
import java.util.*;

public class ChatHandler extends Thread { 
    
   Socket socket; 
   DataInputStream in; 
   DataOutputStream out;
   String name;
   protected static Vector<ChatHandler> handlers = new Vector<ChatHandler>();
    
   public ChatHandler (String name, Socket socket) throws IOException { 
      this.name = name;
      this.socket = socket; 
      in = new DataInputStream (socket.getInputStream());
      out = new DataOutputStream (socket.getOutputStream());
   } 
    
   public void run () { 

      try { 
         broadcast("** " + name + " entered chat **");
         handlers.addElement (this); 

         while (true) { 
             String message = in.readUTF();
             broadcast(name+": " + message); 
         } 

      } catch (IOException ex) { 
         System.out.println("-- Connection to user lost.");
      } finally { 
         handlers.removeElement (this); 
         broadcast("** " + name + " left chat **");
         try { 
             socket.close();
         } catch (IOException ex) { 
            System.out.println("-- Socket to user already closed ?");
         }
      }
   }
    

   protected static void broadcast (String message) { 
      synchronized (handlers) { 
         for (ChatHandler handler : handlers) {
            try { 
                handler.out.writeUTF(message);
            } catch (IOException ex) { 
               handler.stop (); 
            } 
         }
      }
   } 
}

