package SocketExample;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class SimpleHandler implements Runnable {
private Socket sock = null;
private InputStream sockInput = null;
private OutputStream sockOutput = null;
private Thread myThread = null;
public SimpleHandler(Socket sock) throws IOException {
this.sock = sock;
sockInput = sock.getInputStream();
sockOutput = sock.getOutputStream();
this.myThread = new Thread(this);
System.out.println("SimpleHandler: New handler created.");
}
public void start() {
myThread.start();
}
public void run() {
System.out.println("SimpleHandler: Handler run() starting.");
while(true) {
byte[] buf=new byte[1024];
int bytes_read = 0;
try {
bytes_read = sockInput.read(buf, 0, buf.length);
if(bytes_read < 0) {
System.err.println("SimpleHandler: Tried to read from socket, read() returned < 0, Closing socket.");
break;
}
System.err.println("SimpleHandler: Received "+bytes_read
+" bytes, sending them back to client, data="
+(new String(buf, 0, bytes_read)));
sockOutput.write(buf, 0, bytes_read);
sockOutput.flush();
}
catch (Exception e){
e.printStackTrace(System.err);
break;
}
}
try {
System.err.println("SimpleHandler:Closing socket.");
sock.close();
}
catch (Exception e){
System.err.println("SimpleHandler: Exception while closing socket, e="+e);
e.printStackTrace(System.err);
}
}
}