由於項目需要使用Java開發後台伺服器程式,C/C++程式員就要學學Java了。部落格內容用來記錄我的學習過程。Unix/Linux下的幾種網路IO模型在之前的部落格中已經提及到,但是使用的大多數都是Unix/Linux下的系統調用。
部落格內容大多數來自網路資料以及書籍《Netty權威指南》,轉載請註明出處http://blog.csdn.net/Robin__Chou/article/details/54378934,謝謝。
如果想瞭解Unix/Linux下網路IO模型的可以看如下的幾篇相關部落格,裡面大多都是程式碼片段,原理性的講解比較少。
1.Unix/Linux下5種I/O模型
2.多進程並發伺服器
3.多線程並發伺服器
4.IO多工之select
5.IO多工之poll
6.IO多工之epoll
Java作為一門跨平台的語言,當然也會支援上述的幾種IO模型。在JDK1.4之前的版本中,Java對IO的支援並沒有那麼好。直到JDK1.4發布,Java才開始支援非阻塞IO,也是這個版本開始逐漸使用Java開發高效能伺服器。更是到現在有了像Netty,Mina這樣優秀的開源架構。 1.同步阻塞式IO編程
同步阻塞式IO模型中Server端始終有一個“前置”的串連負責和接入進來的用戶端。當有用戶端接入進來時,就建立一個線程用於和該用戶端進行互動,主線程則繼續回到accept阻塞狀態。
相比使用C/C++開發,Java程式的Socket編程則方便了許多。下面執行個體一個時間伺服器的程式,樣本程式設計思路上來源《Netty權威指南》一書。時間伺服器的運行流程就是用戶端串連到伺服器之後,向伺服器發送TIME QUERY命令,Server接受到命令後回送伺服器目前時間給用戶端。程式如下:
import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;/* * BIO模型的問題在於每一個用戶端串連進來,伺服器端就需要建立一個線程來處理用戶端鏈路 * 一個線程只能處理一個用戶端串連,對於高效能,高並發接入情境很難滿足。 * */public class TimeServer { public static void main(String[] args){ int port = 8080; //監聽連接埠號碼為8080 ServerSocket server = null; try { server = new ServerSocket(port); System.out.println("時間伺服器監聽連接埠:" + port); Socket socket = null; while (true) { socket = server.accept(); //accecpt阻塞等待串連 //有用戶端串連進來則建立處理線程,負責和用戶端互動 new Thread(new TimeServerHandler(socket)).start(); } }catch(Exception e){ e.printStackTrace(); }finally { if (server != null) { System.out.println("伺服器端關閉。"); try { server.close(); } catch (IOException e) { e.printStackTrace(); } server = null; } } }}
處理用戶端的線程則可以寫成:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;public class TimeServerHandler implements Runnable { private Socket socket; //與用戶端互動Socket public TimeServerHandler(Socket socket) { //建構函式,傳入串連進來的socket this.socket = socket; } @Override public void run() { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); out = new PrintWriter(this.socket.getOutputStream(), true); String currentTime = null; String body = null; while (true) { body = in.readLine(); //讀取用戶端發送的訊息 if (body == null) //空訊息,則關閉Server端線程 break; System.out.println("伺服器端收到訊息:" + body); /* * 此處處理用戶端請求 */ if("QUERY TIME".equalsIgnoreCase(body)){ currentTime = new java.util.Date(System.currentTimeMillis()).toString(); }else{ currentTime = "未識別的命令"; } out.println(currentTime); } } catch (Exception e) { //關閉接受流 if (in != null) { try { in.close(); } catch (IOException e1) { e1.printStackTrace(); } } //關閉發送流 if (out != null) { out.close(); out = null; } //關閉socket if (this.socket != null) { try { this.socket.close(); } catch (IOException e1) { e1.printStackTrace(); } this.socket = null; } } }}
用戶端程式則比較簡單就是建立串連後發送一條QUERY TIME命令即可。
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;public class TimeClient { public static void main(String[] args) { int port = 8080; Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); out.println("QUERY TIME"); System.out.println("成功發送命令到伺服器端。"); String resp = in.readLine(); //讀取伺服器端返回資訊 System.out.println("目前時間:" + resp); } catch (Exception e) { e.printStackTrace(); } finally { //關閉輸出資料流 if (out != null) { out.close(); out = null; } //關閉輸入資料流 if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } in = null; } //關閉socket串連 if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } socket = null; } } }}程式分析
同步阻塞式IO在每個用戶端串連進來時就建立一個線程來對用戶端進行互動,我們知道每個線程是會佔資源的,而且建立線程的過程也是要佔據資源的。所以對於大量的使用者串連使用同步阻塞IO進行伺服器端程式設計並不合理。這種模型也難以滿足高效能多並發接入的應用場合。 2.使用線程池最佳化的同步阻塞式IO編程
為瞭解決同步阻塞模型中一個用戶端需要建立一個線程進行互動的問題,人們對其進行最佳化,後台通過一個線程池來處理多個用戶端的求解接入。
和上面不同的就是在用戶端串連進來之後,不是去建立一個線程來進行互動,而是直接將用戶端的互動任務丟給線程池去完成。JDK的線程池維護一個訊息佇列和一些活躍的線程來完成訊息佇列中的任務。線程池是可以設定訊息佇列的大小和最大的線程數量的,所以,相比之前的情況,這種方式的資源是可控的,不會導致用戶端串連過多而導致伺服器端資源耗盡。
同樣時間伺服器作為案例,從代碼中可以看出,其實流程上大致相同,不同的就是一個在建立線程進行用戶端互動,而另一個是建立一個線程池,用戶端串連進來之後,直接將用戶端串連丟給線程池去處理。
import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import com.phei.netty.bio.TimeServerHandler;public class TimeServer { public static void main(String[] args){ //監聽連接埠號碼為8080 int port = 8080; ServerSocket server = null; try { server = new ServerSocket(port); System.out.println("時間伺服器監聽連接埠:" + port); Socket socket = null; TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(50, 10000); // 建立IO任務線程池 while (true) { socket = server.accept(); singleExecutor.execute(new TimeServerHandler(socket)); } }catch(Exception e){ e.printStackTrace(); }finally { if (server != null) { System.out.println("伺服器端關閉。"); try { server.close(); } catch (IOException e) { e.printStackTrace(); } server = null; } } }}
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class TimeServerHandlerExecutePool { private ExecutorService executor; public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) { executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maxPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize)); } public void execute(Runnable task) { executor.execute(task); }}
線程池中單個線程的處理還是和同步阻塞式IO模型的Handler相同。用戶端沒有任何不同。使用線程池最佳化的同步阻塞式IO編程雖然解決了上述中的建立線程問題,由於引入了一個訊息佇列,所以如果串連數量一旦很大的時候肯定會導致訊息的延遲,如果某些用戶端的網路不暢,其他的用戶端沒辦法得到及時的響應。而且在隊列滿了之後的用戶端訊息都會被直接拒絕。 3.後記
根據近段時間翻閱的論壇,部落格等等地方來看,使用Java來開發後台伺服器的案例不在少數,甚至是即時性要求較高的遊戲行業也有使用Java開發後台伺服器的案例。手機端APP應用後台使用Java程式開發伺服器的就更多了。此外物聯網技術中也有使用的案例,特別是常常使用自訂的通訊協定的智能家居等。分析使用的原理無外乎有兩點: 使用方便,開發簡單 容易維護,可靠性高
尤其使用Netty,Mina這樣的開源架構,讓開發關注於業務,而不被繁瑣的技術細節所困擾。