publicclass MultiEchoServer { privateintport = 8000; private ServerSocket serverSocket; private ExecutorService executorService; // 线程池 privatefinalintPOOL_SIZE = 4; // 单个CPU时线程池中工作线程的数目 public MultiEchoServer() throws IOException { serverSocket = new ServerSocket(port); executorService = Executors.newFixedThreadPool(Runtime.getRuntime() .availableProcessors() * POOL_SIZE); System.out.println("Server Start"); } publicvoid service() { while (true) { Socket socket = null; try { socket = serverSocket.accept(); executorService.execute(new Handler(socket)); } catch (IOException e) { e.printStackTrace(); } } } publicstaticvoid main(String args[]) throws IOException { new MultiEchoServer().service(); } } class Handler implements Runnable { private Socket socket; public Handler(Socket socket) { this.socket = socket; } private PrintWriter getWriter(Socket socket) throws IOException { OutputStream socketOut = socket.getOutputStream(); returnnew PrintWriter(socketOut, true); } private BufferedReader getReader(Socket socket) throws IOException { InputStream socketIn = socket.getInputStream(); returnnew BufferedReader(new InputStreamReader(socketIn)); } public String echo(String msg) { return"echo:" + msg; } publicvoid run() { try { System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort()); BufferedReader br = getReader(socket); PrintWriter pw = getWriter(socket); String msg = null; while ((msg = br.readLine()) != null) { System.out.println(msg); pw.println(echo(msg)); if (msg.equals("bye")) break; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|