實例說明java
實例代碼:編程
public class BIOServer { public static void main(String[] args) throws Exception { //一、建立一個線程池 ExecutorService threadPool = Executors.newCachedThreadPool(); ServerSocket serverSocket = new ServerSocket(6666); System.out.println("服務器啓動了!!!"); while (true){ //監聽,等待客戶端鏈接 final Socket socket = serverSocket.accept(); System.out.println("鏈接到一個客戶端"); //二、若是有客戶端鏈接了,就建立一個線程,與之通信(單獨寫一個方法) threadPool.execute(new Runnable() { public void run() { //與客戶端進行通信 handler(socket); } }); } } //編寫一個與客戶端通信的handler方法 public static void handler(Socket socket){ //用於接收數據 byte[] bytes = new byte[1024]; //經過socket獲取輸入流 InputStream inputStream = null; try { System.out.println("線程id="+Thread.currentThread().getId()+"名字="+Thread.currentThread().getName()); inputStream = socket.getInputStream(); //循環讀取客戶端發送的數據 while(true){ int read = inputStream.read(bytes); if (read!=-1){ //輸出客戶端發送的數據 System.out.println(「收到信息:」+new String(bytes,0,read)); }else{ break; } } } catch (IOException e) { e.printStackTrace(); }finally { System.out.println("關閉與客戶端的鏈接......"); try { inputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
測試結果:服務器
服務器啓動了!!! 鏈接到一個客戶端 線程id=12名字=pool-1-thread-1 收到消息:nihao