33. bio and nio

1. Bio network model

1.1 Schematic diagram of bio network model

When a single client initiates a request to the server, the request sequence is as follows:
image

When multiple clients initiate requests to a server, the order of requests is as follows:
image

1.2 Disadvantages of bio network model

1. Blocking I/O

服务器端的线程会因为阻塞I/O,一直阻塞,等待客户端的请求。
若客户端一直不发起,服务端的业务线程会一直存在。

2. Poor elastic scalability

因为一个客户端对应一个服务端的业务线程,那么客户端和服务端线程数是1比1的关系,再好的机器也难以承受过多的线程。

3. Multithreading consumes resources

线程的创建销毁、大量的线程存在服务端,服务端的cpu调度资源都会存在影响

2. NIO network model

2.1 Schematic diagram of nio network model

When a single client initiates a request to the server, the request sequence is as follows:
image

2.2 Improvement of nio network model

1. Non-blocking I/O

nio模型是基于非阻塞式I/O构建出来的,服务器端提供一个单线程的select,统一管理所有客户端接入的socket链接,并负责监听每个链接所关心的事件。

2. Strong elastic expansion ability

因为服务端不是多个线程来处理,而是一个线程就可以处理所有请求,所有客户端和服务端线程数是1比N的关系,理论上可以接入无限的请求。

3. Single thread saves resources

减少了线程的创建和销毁,以及线程上下文的切换问题。

3. NIO core - Channel (channel)

3.1 Introduction to Channels

1. Two-way

信息传输的通道,jdk的nio是对输入输出的方式的另一种抽象,类比bio中的流的概念。
不同的是流是单向传输,分输入流输出流。而通道支持双向传输,一个channel既可读又可写。

2. Non-blocking

传统流是阻塞模式,而channel可以工作在非阻塞模式下。

3. Operation uniqueness

操作channel的唯一方式是buffer,通过buffer操作channel实现数据块的回写

3.2 Channel implementation class

1. File class: FileChannel - stream for reading and writing files 2. UDP class: DatagramChannel - used for UDP data reading and writing 3. TCP class: ServerSocketChannel/SocketChannel based on TCP data reading and writing

3.3 bio socket and nio channel code implementation

Bio's socket code implements logic
image

Nio's channel code implements logic
image

Four, NIO core - buffer (buffer)

4.1 Introduction to buffers

作用 - 读写channel中的数据或者将数据写到channnel中。
本质 - 一块内存区域。这块内存能读数据,写数据,被nio封装成了一个buffer对象,提供了一系列API。

4.2 buffer properties

1.Capacity:容量 - 表明数组可以容纳多少字节,如果写入的字节数超过最大容量,那么需要清空后,才能继续往里面写入数据。
2.Position: 位置 - position表示当前位置,初始化为0,当一个byte写入后,position会移动到下一个可插入的数据单元。position最大可为容量减1
3.Limit:上限(写模式下) -limit表示最多能往buffer里写入多少数据,此模式下limit等于Capacity。
4.Limit:上限(读模式下) -limit表示最多能从buffer里读多少数据,这时limit会被设置成Position值
5.Mark:标记 - 表示一个特定的position位置,可以通过调用buffer的reset方法恢复到这个position位置。

4.3 buffers的API

1. Initialization
image

2. Write data
image

3. Switch from write mode to read mode
image

4. Read a byte
image

5. Set the mark mark
image

6. Go back to the flag
image

7. Reset properties
image

Five, NIO core - Select (selector)

5.1 Introduction

1.作用 - I/O就绪选择
2.地位 - NIO网络编程的基础
3.定义 - select是java的nio中能够检测1到多个nio通道,并能够知晓通道是否为诸如读写事件做好准备的组件,通过他,一个单独的线程就可以管理多个channel,从而管理多个链接。

5.2 Core APIs

image

5.3 Introduction to SelectionKey

1.四种就绪状态常量
    connect 连接就绪
    accept  接收就绪
    read    读就绪
    write   写就绪

Six, NIO programming implementation steps

image
image
image

7. Summary

image
image
image
image
image

Guess you like

Origin blog.csdn.net/yang134679/article/details/131777508