漫談Java IO之普通IO流與BIO伺服器

來源:互聯網
上載者:User

標籤:傳統   charset   local   post   服務   html   就是   監聽   輸入輸出資料流   

今天來複習一下基礎IO,也就是最普通的IO。

  1. 網路IO的基本知識與概念
  2. 普通IO以及BIO伺服器
  3. NIO的使用與伺服器Hello world
  4. Netty入門與伺服器Hello world
  5. Netty深入淺出
輸入資料流與輸出資料流

Java的輸入資料流和輸出資料流,按照輸入輸出的單元不同,又可以分為位元組流和字元流的。

JDK提供了很多輸入資料流和輸出資料流,比如:

位元組流可以按照不同的變數類型進行讀寫,而字元流則是基於字元編碼的。不同的字元編碼包含的位元組數是不一樣的,因此在使用字元流時,一定要注意編碼的問題。

讀寫位元組的輸入輸出資料流操作
// 位元組輸入資料流操作InputStream input = new ByteArrayInputStream("abcd".getBytes());int data = input.read();while(data != -1){    System.out.println((char)data);    data = input.read();}// 位元組輸出資料流ByteArrayOutputStream output = new ByteArrayOutputStream();output.write("12345".getBytes());byte[] ob = output.toByteArray();
字元的輸入輸出資料流操作
// 字元輸入資料流操作Reader reader = new CharArrayReader("abcd".toCharArray());data = reader.read();while(data != -1){    System.out.println((char)data);    data = reader.read();}// 字元輸出資料流CharArrayWriter writer = new CharArrayWriter();writer.write("12345".toCharArray());char[] wc = writer.toCharArray();
關閉流

流開啟後,相當於佔用了一個檔案的資源,需要及時的釋放。傳統的標準關閉的方式為:

// 位元組輸入資料流操作InputStream input = null;try {    input = new ByteArrayInputStream("abcd".getBytes());    int data = input.read();    while (data != -1) {        System.out.println((char) data);        // todo        data = input.read();    }}catch(Exception e){    // todo}finally {    if(input != null) {        try {            input.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

在JDK1.7後引入了try-with-resources的文法,可以在跳出try{}的時候直接自動釋放:

try(InputStream input1 = new ByteArrayInputStream("abcd".getBytes())){   //}catch (Exception e){    //}
IOUtils

直接使用IO的API還是很麻煩的,網上的大多數教程都是各種while迴圈,操作很麻煩。其實apache common已經提供了一個工具類——IOUtils,可以方便的進行IO操作。

比如IOUtils.readLines(is, Charset.forName("UTF-8"));可以方便的按照一行一行讀取.

BIO阻塞伺服器

基於原始的IO和Socket就可以編寫一個最基本的BIO伺服器。

概要: 這個模型很簡單,就是主線程(Acceptor)負責接收串連,然後開啟新的線程專門負責串連處理用戶端的請求。

import io.netty.util.CharsetUtil;import java.io.IOException;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class PlainOioServer {    public void serve(int port) throws IOException {        // 開啟Socket伺服器,並監聽連接埠        final ServerSocket socket = new ServerSocket(port);        try{            for(;;){                // 輪訓接收監聽                final Socket clientSocket = socket.accept();                try {                    Thread.sleep(500000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("accepted connection from "+clientSocket);                // 建立新線程處理請求                new Thread(()->{                   OutputStream out;                   try{                       out = clientSocket.getOutputStream();                       out.write("Hi\r\n".getBytes(CharsetUtil.UTF_8));                       out.flush();                   } catch (IOException e) {                       e.printStackTrace();                   } finally {                       try{                           clientSocket.close();                       } catch (IOException e) {                           e.printStackTrace();                       }                   }                }).start();            }        } catch (IOException e){            e.printStackTrace();        }    }    public static void main(String[] args) throws IOException {        PlainOioServer server = new PlainOioServer();        server.serve(5555);    }}

然後執行telnet localhost 5555,就能看到返回結果了。

這種阻塞模式的伺服器,原理上很簡單,問題也容易就暴露出來:

  1. 服務端與用戶端的串連相當於1:1,因此如果串連數上升,伺服器的壓力會很大
  2. 如果主線程Acceptor阻塞,那麼整個伺服器將會阻塞,單點問題嚴重
  3. 線程數膨脹後,整個伺服器效能都會下降

改進的方式可以基於線程池或者訊息佇列,不過也存在一些問題:

  1. 線程池的數量、訊息佇列後端伺服器並發處理數,都是並發數的限制
  2. 仍然存在Acceptor的單點阻塞問題

接下來,將會介紹基於Nio的非阻塞伺服器模式,如果忘記什麼是IO多工,可以回顧前面一篇分享。敬請期待吧...

漫談Java IO之普通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.