package SimpleChatOne;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class Handler implements Runnable {
private final static int READ_BUF_SIZE=1024;
private final static int SAVE_BUF_SIZE=10240;
private Socket sock = null;
private Switchboard switchboard = null;
private InputStream sockInput = null;
private OutputStream sockOutput = null;
private Thread myThread = null;
private byte[] bufferedData = null; private boolean loggedIn = false;
private String name="NotLoggedIn";
public String getName() { return name; }
public Handler(Socket sock, Switchboard switchboard, String messageOfTheDay) throws IOException {
this.sock = sock;
this.switchboard = switchboard;
sockInput = sock.getInputStream();
sockOutput = sock.getOutputStream();
bufferedData = new byte[SAVE_BUF_SIZE];
name = sock.getRemoteSocketAddress().toString();
myThread = new Thread(this);
try {
sockOutput.write(messageOfTheDay.getBytes(), 0, messageOfTheDay.getBytes().length);
sockOutput.flush();
}
catch (IOException e) {
}
System.out.println(this.getClass().getName()+": New handler created.");
}
public void start() {
myThread.start();
}
public synchronized void write(byte[] data, int numBytesRead) {
try {
sockOutput.write(data, 0, numBytesRead);
sockOutput.flush();
}
catch (IOException e){
try {
System.err.println(this.getClass().getName()+": Error writing to socket, closing socket.");
sock.close();
}
catch (Exception e2){
System.err.println(this.getClass().getName()+": Exception while closing socket, e2="+e2);
e.printStackTrace(System.err);
}
switchboard.remove(this);
}
}
public void process(byte[] data, int numBytes) {
switchboard.sendToAllConnections(this, data, numBytes);
}
public void run() {
System.out.println(this.getClass().getName()+": Handler run() starting.");
byte[] buf = new byte[READ_BUF_SIZE];
while(true) {
int numBytesRead = 0;
try {
numBytesRead = sockInput.read(buf, 0, buf.length);
if(numBytesRead < 0) {
System.err.println(this.getClass().getName()+": Tried to read from socket, read() returned < 0, Closing socket.");
break;
}
System.err.println(this.getClass().getName()+": Received "+numBytesRead+" bytes, sending to other clients: "+new String(buf));
process(buf, numBytesRead);
}
catch (Exception e){
e.printStackTrace(System.err);
break;
}
}
try {
System.err.println(this.getClass().getName()+":Closing socket.");
sock.close();
}
catch (Exception e) {
System.err.println(this.getClass().getName()+":Exception while closing socket, e="+e);
e.printStackTrace(System.err);
}
switchboard.remove(this);
}
}