import java.math.BigInteger; import java.net.*; import java.io.*; public class FibServer { // This is the naive approach. We should do this with // a thread pool, and I may add that later; but that would // be so much easier in Java 5, I'll do the Java 5 solution // first. public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(8234); while (true) { Socket s = ss.accept(); Responder r = new Responder(s); r.start(); } } private static class Responder extends Thread { private Socket socket; Responder(Socket s) { this.socket = s; } public void run() { try { InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "US-ASCII")); String s = reader.readLine(); int input = Integer.parseInt(s); BigInteger result = fib(input); OutputStream out = socket.getOutputStream(); String output = result.toString(); out.write(output.getBytes("US-ASCII")); out.write('\r'); out.write('\n'); out.flush(); } catch (Exception ex) { // no big deal; or we could write an error message. // If so, I'd wanted a nested try block above. } finally { try { socket.close(); } catch (IOException ex) { //nothing we can do } } } private BigInteger fib(int input) { if (input < 0) { throw new IllegalArgumentException("Negative number"); } BigInteger low = BigInteger.ZERO; BigInteger high = BigInteger.ONE; for (int i = 0; i < input; i++) { BigInteger temp = high; high = high.add(low); low = temp; } return low; } } }