gvsu/cs654/lab5/partI/ChatHandler.java
josh 2feecca1e6 cs654/lab5: chat working
git-svn-id: svn://anubis/gvsu@15 45c1a28c-8058-47b2-ae61-ca45b979098e
2008-02-17 03:37:15 +00:00

58 lines
1.5 KiB
Java

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 ();
}
}
}
}
}