Java IO編程全解(二)——傳統的BIO編程

來源:互聯網
上載者:User

標籤:oid   演化   margin   unknown   網路   sign   order   java   關係   

前面講到:Java IO編程全解(一)——Java的I/O演化之路

  網路編程的基本模型是Client/Server模型,也就是兩個進程之間進行相互連信,其中服務端提供位置資訊(綁定的IP地址和監聽連接埠),用戶端通過串連操作向服務端監聽的地址發起串連請求,通過三向交握建立串連,如果串連建立成功,雙方就可以通過網路通訊端(Socket)進行通訊。

  在基於傳統同步阻塞模型開發中,ServerSocket負責綁定IP地址,啟動監聽連接埠;Socket負責發起串連操作。串連成功之後,雙方通過輸入和輸出資料流進行同步阻塞式通訊。

  以經典的時間伺服器(TimeServer)為例,通過程式碼分析來回顧和熟悉下BIO編程。

1. BIO通訊模型圖

  如BIO的服務端通訊模型:採用BIO通訊模型的服務端,通常由一個獨立的Acceptor線程負責監聽用戶端的串連,它接收到用戶端串連請求之後為每個用戶端建立一個新的線程進行鏈路處理,處理完成之後,通過輸出資料流返回應答給用戶端,線程銷毀。這就是典型的一請求一應答通訊模型。

圖1  同步阻塞I/O服務端通訊模型(一用戶端一線程)

  該模型最大的問題就是缺乏Auto Scaling能力,當用戶端並發訪問量增加後,服務端的線程個數和用戶端並發訪問數呈1:1 的正比關係,猶豫線程是Java虛擬機器非常寶貴的系統資源,當線程數膨脹之後,系統的效能將急劇下降,隨著並發訪問量的繼續增大,系統會發生線程堆疊溢位、建立新線程失敗等問題,並最終導致進程宕機或者僵死,不能對外提供服務。

2. 同步阻塞式I/O建立的TimeServer
package joanna.yan.bio;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class TimeServer {    public static void main(String[] args) {        int port=9090;        if(args!=null&&args.length>0){            try {                port=Integer.valueOf(args[0]);            } catch (Exception e) {                // 採用預設值            }        }                ServerSocket server=null;                try {            server=new ServerSocket(port);            System.out.println("The time server is start in port:"+port);            Socket socket=null;            while(true){//通過一個無限迴圈來監聽用戶端的串連                socket=server.accept();//如果沒有用戶端接入,則主線程阻塞在ServerSocket的accept操作上。                new Thread(new TimeServerHandler(socket)).start();            }        } catch (IOException e) {            e.printStackTrace();        }finally{            if(server!=null){                System.out.println("The time server close");                try {                    server.close();                    server=null;                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}
package joanna.yan.bio;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;import java.util.Date;public class TimeServerHandler implements Runnable{    private Socket socket;        public TimeServerHandler(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){                    break;                }                System.out.println("The time server receive order:"+body);                //如果請求訊息為查詢時間的指令"QUERY TIME ORDER"則擷取當前最新的系統時間。                currentTime="QUERY TIME ORDER".equalsIgnoreCase(body) ?                         new Date(System.currentTimeMillis()).toString() : "BAD ORDER";                out.println(currentTime);            }        } catch (IOException e) {            e.printStackTrace();        }finally{            if(in!=null){                try {                    in.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if(out!=null){                out.close();                out=null;            }            if(this.socket!=null){                try {                    this.socket.close();                    this.socket=null;                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}
3. 同步阻塞式I/O建立的TimeClient

  用戶端通過Socket建立,發送查詢時間伺服器的“QUERY TIME ORDER”指令,然後讀取服務端的響應並將結果列印出來,隨後關閉串連,釋放資源,程式退出執行。

package joanna.yan.bio;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;public class TimeClient {    public static void main(String[] args) {        int port=9090;        if(args!=null&&args.length>0){            try {                port=Integer.valueOf(args[0]);            } catch (Exception e) {                // 採用預設值            }        }                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 ORDER");            System.out.println("Send order 2 server succeed.");            String resp=in.readLine();            System.out.println("Now is:"+resp);                    } catch (UnknownHostException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally{            if(out!=null){                out.close();                out=null;            }            if(in!=null){                try {                    in.close();                } catch (IOException e) {                    e.printStackTrace();                }                in=null;            }            if(socket!=null){                try {                    socket.close();                } catch (IOException e) {                    e.printStackTrace();                }                socket=null;            }        }    }}

  我們發現,BIO主要的問題在於每當有一個新的用戶端請求接入時,服務端必須建立一個新的線程處理新接入的用戶端鏈路,一個線程只能吃力一個用戶端串連。在高效能伺服器應用領域,往往需要面向成千上萬個用戶端的並發串連,這種模型顯然無法滿足高效能、高並發接入的情境。

  為了改進一線程一串連模型,後來又演化出了一種通過線程池或者訊息佇列實現1個或者多個線程處理N個用戶端的模型,由於它的底層通訊機制依然使用同步阻塞I/O,所以被稱為“偽非同步”。後面我們將通過對偽非同步代碼的分析,看看偽非同步能否滿足我們對高效能、高並發接入的訴求。

  如果此文對您有協助,打賞我一下吧~

 

Java IO編程全解(二)——傳統的BIO編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.