import java.io.*; import java.net.*; import java.util.*; public class ChatHandler implements Runnable { protected Socket socket; public ChatHandler (Socket socket) { this.socket=socket; } protected DataInputStream dataIn; protected DataOutputStream dataOut; protected Thread listener; public synchronized void start() { if (listener == null) { try { dataIn = new DataInputStream (new BufferedInputStream(socket.getInputStream())); dataOut=new DataOutputStream (new BufferedOutputStream(socket.getOutputStream())); listener = new Thread(this); listener.start(); } catch (IOException ignore) { } } } public synchronized void stop() { if (listener != null) { try { if (listener != Thread.currentThread()) listener.interrupt(); listener=null; dataOut.close(); } catch (IOException ignored) { } } } protected static Vector handlers = new Vector(); public void run() { try { handlers.addElement (this); while (!Thread.interrupted ()) { String message= dataIn.readUTF(); String name=new String(listener.getName()+" > "); String mess=new String(name+message); broadcast (mess); } } catch (EOFException ignored) { } catch (IOException ex) { if (listener==Thread.currentThread()) ex.printStackTrace(); } finally { handlers.removeElement (this); } stop (); } protected void broadcast (String message) { synchronized (handlers) { Enumeration enum = handlers.elements (); while ( enum.hasMoreElements()) { ChatHandler handler=(ChatHandler) enum.nextElement(); try { handler.dataOut.writeUTF(message); handler.dataOut.flush(); } catch (IOException ex) { handler.stop(); } } } } }