rendered paste bodyimport java.net.*;
import java.io.*;
import java.util.*;
public class ServerThread implements Runnable {
private Socket socket = null;
public ServerThread(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()));
System.out.println("1");
String message="has logged on\n";
broadcast(message);
listener = new Thread(this);
listener.start();
} catch (IOException ignored) {}
}
}
public synchronized void stop() {
if (listener != null) {
try {
if (listener != Thread.currentThread())
listener.interrupt();
listener = null;
dataOut.close();
String msg= "logged off.\n";
broadcast(msg);
} catch (IOException ignored) {
}
}
}
protected static Vector handlers = new Vector();
public void run() {
try {
System.out.println("2");
handlers.addElement(this);
while (!Thread.interrupted()) {
String message = dataIn.readUTF();
broadcast(message);
}
} 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()) {
ServerThread handler = (ServerThread) enum.nextElement();
try {
handler.dataOut.writeUTF(message);
handler.dataOut.flush();
} catch (IOException ex) {
handler.stop();
}
}
}
}
protected void broadcastNew(String message) {
synchronized (handlers) {
Enumeration enum = handlers.elements();
while (enum.hasMoreElements()) {
ServerThread handler = (ServerThread) enum.nextElement();
try {
handler.dataOut.writeUTF(message);
handler.dataOut.flush();
} catch (IOException ex) {
handler.stop();
}
}
}
}
}