ExecutorHttpd.java Source code

Java tutorial

Introduction

Here is the source code for ExecutorHttpd.java

Source

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExecutorHttpd {
    ExecutorService executor = Executors.newFixedThreadPool(3);

    public void start(int port) throws IOException {
        final ServerSocket ss = new ServerSocket(port);
        while (!executor.isShutdown())
            executor.submit(new TinyHttpdConnection(ss.accept()));
    }

    public void shutdown() throws InterruptedException {
        executor.shutdown();
        executor.awaitTermination(30, TimeUnit.SECONDS);
        executor.shutdownNow();
    }

    public static void main(String argv[]) throws Exception {
        new ExecutorHttpd().start(Integer.parseInt(argv[0]));
    }
}

class TinyHttpdConnection implements Runnable {
    Socket client;

    TinyHttpdConnection(Socket client) throws SocketException {
        this.client = client;
    }

    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), "8859_1"));
            OutputStream out = client.getOutputStream();
            PrintWriter pout = new PrintWriter(new OutputStreamWriter(out, "8859_1"), true);
            String request = in.readLine();
            System.out.println("Request: " + request);

            byte[] data = "hello".getBytes();
            out.write(data, 0, data.length);
            out.flush();
            client.close();
        } catch (IOException e) {
            System.out.println("I/O error " + e);
        }
    }
}