Random talk about Java io's normal IO stream and Bio server

Source: Internet
Author: User

Today to review the basic IO, which is the most common IO.

    1. Basic knowledge and concepts of network IO
    2. General IO and Bio server
    3. Use of NiO with server Hello World
    4. Netty Getting Started with server Hello World
    5. Netty in Layman's
Input stream and output stream

Java input and output streams, according to the input and output of the unit, but also can be divided into byte stream and character stream.

The JDK provides a number of input and output streams, such as:

Byte stream can be read and written according to different variable types, while character stream is based on characters encoding. The different character encodings contain not the same number of bytes, so when you use character streams, you must be aware of the encoding problem.

Input-output stream operation for read-write bytes
// 字节输入流操作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();
Input and output stream operations for characters
// 字符输入流操作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();
Close the stream

When the stream is opened, it is equivalent to a resource that occupies a file and needs to be released in a timely manner. The traditional way of closing the standard is:

// 字节输入流操作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();        }    }}

After JDK1.7 introduced the try-with-resources syntax, can be automatically released when jumping out of the try{}:

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

The API to use IO directly is cumbersome, and most tutorials on the web are a variety of while loops that are cumbersome to operate. In fact, Apache Common has provided a tool class--ioutils, which can be easily used for IO operation.

For example IOUtils.readLines(is, Charset.forName("UTF-8")); , it can be easily read in one line.

Bio Blocking server

Based on the original IO and socket, you can write a basic bio server.

Summary: This model is simple, that is, the main thread (acceptor) is responsible for receiving the connection, and then opening a new thread that is specifically responsible for connection processing of the client's request.

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 Ioexcepti        On {//Open the socket server and listen for port final serversocket socket = new ServerSocket (port); try{for (;;)                {//Rotation receive monitor final Socket clientsocket = Socket.accept ();                try {thread.sleep (500000);                } catch (Interruptedexception e) {e.printstacktrace ();                } System.out.println ("Accepted connection from" +clientsocket);                   Create a new thread processing request 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); }}

Then telnet localhost 5555 , you can see the return result.

This blocking mode of the server, the principle is very simple, the problem is easy to expose:

    1. The server's connection to the client is equivalent to 1:1, so if the number of connections goes up, the pressure on the servers will be great.
    2. If the main thread acceptor blocked, then the entire server will be blocked, a single point of serious
    3. When the number of threads expands, the performance of the entire server drops

The improvements can be based on the thread pool or Message Queuing , but there are some problems:

    1. The number of thread pools, the number of concurrent processing of Message Queuing backend servers, is the limit of concurrency
    2. There are still acceptor single point blocking problems

Next, a non-blocking server model based on NIO will be introduced, and if you forget what IO multiplexing is, you can review the previous share. Please look forward to it ...

Random talk about Java io's normal IO stream and Bio server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.