int port;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
port = 0;
}
try {
ServerSocket server = new ServerSocket(port, 1);
System.out.println("Listening for connections on port "
+ server.getLocalPort());
while (true) {
Socket connection = server.accept();
try {
System.out.println("Connection established with "
+ connection);
Thread input = new InputThread(connection.getInputStream());
input.start();
Thread output
= new OutputThread(connection.getOutputStream());
output.start();
// wait for output and input to finish
try {
input.join();
output.join();
}
catch (InterruptedException ex) {
}
}
catch (IOException ex) {
System.err.println(ex);
}
finally {
try {
if (connection != null) connection.close();
}
catch (IOException ex) {}
}
}
}
catch (IOException ex) {
e.printStackTrace();
}