import java.net.*;
import java.io.*;
public class MTEchoServer {
public static void main(String[] args) throws IOException {
int port = 9999;
ServerSocket serverSocket = null;
Socket clientSocket = null;
EchoSlave slave = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port + ".");
System.exit(1);
}
try {
while (true) {
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
slave = new EchoSlave (clientSocket);
slave.start ();
}
} finally {
serverSocket.close();
}
}
}
class EchoSlave extends Thread {
Socket clientSocket = null;
public EchoSlave (Socket clientSocket) {
this.clientSocket = clientSocket;
}
//gives this thread a new port so the server can still listen on the original port
public void run () {
OutputStream cout = null;
InputStream cin = null;
int aByte;
try {
cout = clientSocket.getOutputStream();
cin = clientSocket.getInputStream();
while ((aByte = cin.read()) >= 0)
{
cout.write (aByte);
}
} catch (IOException e) {
} finally {
try {
cin.close();
cout.close();
clientSocket.close();
} catch (IOException e) { }
}
}
}