Netty Quick Start (02) Java I / O (BIO) Introduction

About BIO

Java I / O, also known as Blocking I / O, which is blocking I / O.

file

BIO process is relatively simple, the creation of a ServerSocket to listen, wait for a connection at the server. Socket client creates a connection over, the server can receive a connection request to establish a connection. After the connection is established, the server and the client can perform a data communication through a streaming the API, some read and write operations.

Examples of single-threaded BIO

BIO's look at an example, the server to create a ServerSocket, then wait for a connection (accept is blocked):

file

After the connection over the IO read and write data flow mode, processing as follows:

file

Socket client initiates a connection, then the same manner as with read and write IO data stream:

file

The code above I believe many people have written, and are familiar with, you can see BIO single-threaded programming logic is clear, content is simple (but inefficient ...), the results are as follows:

file

file

The whole process is a single-threaded program, and if again this time a client connects, the new client will not be able to establish a connection, because the connection has been blocked in a while loop.

Multithreading BIO example

BIO look at an example of a multi-threaded, the same server to create a ServerSocket, then wait for a connection (accept is blocked), the difference is that a connection is to start a new thread to handle:

file

The method of treatment as a thread, and almost single-threaded operation:

file

Multithreading is reflected in the service, the client base has not changed the wording, let's start a server and three clients, view the results:

file

file

file

file

The obvious drawback is that this way when connected and more, the number of threads will be ringing off the hook, can not support high concurrent situation. Although you can use the thread pool to protect the machine, but can not solve the problem fundamentally high concurrency. Here is an example using a thread pool:

file

As client-side code, the presentation is no longer here.

Code Address: https://gitee.com/blueses/netty-demo 01

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin www.cnblogs.com/guos/p/12187256.html