傳統的socket io中,若是須要同時接受多個鏈接的時候。必需要使用多線程,爲每個鏈接建立一個線程。這樣在鏈接數量比較大的狀況,線程的數量也隨之變大。雖然這樣編程簡單,可是缺點也十分的明顯,就是大量的線程佔用的大量的資源(內存和cpu的開銷)。無論怎麼樣,咱們先編寫一段程序,瞭解一下io編程的特色。(ps:程序不是很完善,請多擔待)編程
單線程服務端程序:網絡
public class SingleThreadSocketServer { public static void main(String[] args) { ServerSocket serverSocket = null; BufferedReader bufferedReader = null; Socket socket = null; try { serverSocket = new ServerSocket(9999); //建立一個端口是9999的socket服務 socket = serverSocket.accept(); //一直監聽端口是否有鏈接進來,沒有鏈接進來的時候,這個方法會一直阻塞在這裏。 bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String str; while((str = bufferedReader.readLine()) != null) { //若是客戶端發送quit消息服務端斷開鏈接 if("quit".equals(str)) { break; } System.out.println("收到客戶端發來的消息:" + str); } } catch (IOException e) { e.printStackTrace(); }finally { try { System.out.println("關閉鏈接!"); bufferedReader.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
注意:上面的單線程服務端有着很大的缺點,就是隻能接受一次鏈接,接受完一次鏈接以後,通信完事以後就關閉了。這很明顯不是很爽的一個體驗,因此咱們要進行優化。多線程
多線程服務端程序:socket
線程類:優化
public class SocketThread implements Runnable { private int index; private Socket socket; public SocketThread(Socket socket, int index) { this.socket = socket; this.index = index; } public void run() { InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { inputStream = socket.getInputStream(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); String content; while ( (content =bufferedReader.readLine()) != null) { System.out.println("第" + index + "個鏈接發來消息:" + content); } } catch (IOException e) { e.printStackTrace(); }finally { try{ System.out.println("關閉" + index + "號鏈接!"); bufferedReader.close(); inputStreamReader.close(); inputStream.close(); }catch (IOException e) { } } } }
服務端:ui
public class MoreThreadSocketServer { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(9999); //建立一個socket服務,而且綁定9999端口 int index = 0; while (true) { index ++; Socket socket = serverSocket.accept(); Thread thread = new Thread(new SocketThread(socket, index)); thread.start(); } } catch (IOException e) { e.printStackTrace(); } } }
總結:從兩個程序的對比能夠看出來,基於io的socket編程是阻塞的,並且不能同時保持多個鏈接。若是要實現這個功能,必需要使用多線程。每個鏈接都須要一個線程來保持。這兩個缺點在基於nio網絡編程中將解決這個問題。this