import java.io.*; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.net.ServerSocket; import java.net.Socket; class NetworkService implements Runnable { private final ServerSocket serverSocket; private final ExecutorService pool; public NetworkService(int port, int poolSize) throws IOException { serverSocket = new ServerSocket(port); pool = Executors.newFixedThreadPool(poolSize); } public void run() { // run the service try { for (int k = 0; k < 30; k++) { pool.execute(new Handler(serverSocket.accept())); } } catch (IOException e) { System.out.println(e.getMessage()); } finally { pool.shutdown(); } } } class Handler implements Runnable { private final Socket socket; Handler(Socket socket) { this.socket = socket; } public void run() { // read and service request on socket char[] buffer = new char[1024]; int count = 0; int n = 0; try { InputStreamReader reader = new InputStreamReader ( socket.getInputStream() ); OutputStreamWriter writer = new OutputStreamWriter( socket.getOutputStream() ); while (true) { //until client closes connection try { n = reader.read(buffer, 0, buffer.length); writer.write(buffer, 0, n); } catch (IOException e) { break; } if (n <= 0) break; // no more data to read count += n; } } catch (Exception e) { System.out.println("Server count = " + count); } finally { try { socket.close(); } catch (IOException e) { System.out.println("IOException while closing connected socket"); } } } } class ExecutorServiceExample { public static final int DEFAULT_PORT = 9876; public static final int DEFAULT_POOL_SIZE = 8; public static void main(String[] args) throws IOException { int port = DEFAULT_PORT; int poolSize = DEFAULT_POOL_SIZE; if (args.length >= 1) { port = Integer.parseInt(args[0]); if (args.length >= 2) poolSize = Integer.parseInt(args[1]); } NetworkService service = new NetworkService(port, poolSize); Thread poolService = new Thread(service); poolService.start(); } }