package io; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by dingshuangkun on 2017/12/30. */ public class Server { private static int count = 1; public static void main(String[] arges) throws Exception { ExecutorService es= Executors.newFixedThreadPool(20); ServerSocket ss = new ServerSocket(8080); System.out.println("服務器啓動"); while (true) { final Socket socket = ss.accept(); System.out.println("新建客戶端" + count); count++; es.submit(()->{ handler(socket); }); } } public static void handler(Socket socket) { try { byte[] b = new byte[1024]; InputStream inputStream = socket.getInputStream(); while (true) { int read = inputStream.read(b); if (read != -1) { System.out.println(new String(b,0,read)); }else { break; } } } catch (IOException e) { e.printStackTrace(); }finally { System.out.println("socket 關閉"); try { socket.close(); }catch (IOException e){ e.printStackTrace(); } } } }
吧 handle(Socket socket) 改爲僞異步的。用線程池提交java
多線程能夠管理多個連接(一個線程對應一個連接)。可是隨着連接的增多,會佔用大量的線程,浪費系統資源服務器