tags: Netty java Development language rear end
- Hey everyone, I amJava small white 2021。
- The programmer of the halfway is in the development of aircraft, and the opportunity to find a more interesting thing under the development of a surveying court, and stepped into the programmed world ... PS: At the same time, it is also a car that loves to travel. expert!
- Purpose: Record your own learning history, I hope you can help you, please refer to you! Learn exchange together

Thread groupThis group contains multiple event loop threads, each event loop thread is nioeventloop.Bootstrap means booting, a Netty application is usually starting by a bootstrap, the main function is to configure the entire Netty program, in series, the BootStrap class in Netty is the boot boot class of the client program, ServerBootstrap is the service-enable boot class
All IO operations in Netty are asynchronous and cannot beware of whether the message is properly processed.
But you can wait for a while to perform or directly register a monitored, the specific time is through Future and ChannelFutures, which can be registered with a monitor, and the listener will automatically trigger the registration monitoring event when the operation is performed.
Netty network communication components can be used to perform network I / O operations. Channel provides users:
- The status of the channel current network connection (is open? Is it connected, etc.)
- Configuration parameters for network connections (receiving buffer size)
- Provide asynchronous network I / O operation (establishment of connection, reading, binding port), asynchronous call means that any I / O call will return immediately, and does not guarantee the I / O operation of the autumn in the end of the call. .
- Call now returns a CHANNELFUTURE instance, by registering the listener to CHANELFUTURE, you can operate successfully, fail, or cancel the callback notification call.
- Support the associated I / O operation and the corresponding procedure. Different protocols, different blocked types of links have different CHANNEL types and corresponding.
Here are some common Channel types:
NiosocketChannel, asynchronous client TCP Socket connection.
NioserversocketChannel, asynchronous server-side TCP Socket connection.
NiodatagramChannel, asynchronous UDP connection.
NiosctPChannel, asynchronous client SCTP connection.
NiosCTPServerChannel, asynchronous SCTP server-side connection.
These channels covers UDP and TCP network IOs and file IO.
Netty is based on the Selector object to implement I / O multi-channel reuse, and you can listen to multiple connected Channel events through Selector. When you register with the Channel in a Selector, the mechanism within Selector can automatically query if these registered Channel has a ready I / O event (eg readable, writable, network connection completion, etc.), so The program can easily manage multiple Channel using a thread.
A thread and task queue is maintained in NiOEventLoop, support asynchronous submission execution tasks, and the thread is started to call the NiOEventLoop RUN method, perform I / O tasks and non-I / O tasks:
I / O mission, Ready events in SelectionKey, such as Accept, Connect, Read, Write, etc., triggered by ProcessSelectedKeys method
Non-I / O tasks, add to tasks in TaskQueue, such as register0, bind0 and other tasks, triggered by RunalLTasks method
NiOEventLoopGroup, mainly manages EventLoop lifecycle, which can be understood as a thread pool, which maintains a set of threads, each thread (nioeventloop) responsible for handling multiple Channel, and a Channel only corresponds to a thread.
ChannelHandler is an interface, processing I / O events, or blocking I / O operations, forwarding it to the next handler in its CHANNELPIPELINE.
ChannelHandler itself does not provide many ways, because this interface has many methods need to be realized, and can inherit its subclasses during the trial
ChannelInBoundHandler is used to process an inbound I / O event.
ChannelOutBoundHandler is used to process outbound I / O operations.
Or use the following adapter classes
ChannelInBoundHandleRadapter is used to process an inbound I / O event.
ChannelOutBoundHandleRadapter is used to process outbound I / O operations.
Save all Context information related to Channel while managing the ChannelHandler object.
Save ChannelHandler's List for handling or intercepting the incoming events of Channel and outbound operations.
ChannelPipeline implements a high-grade intercept filter mode that allows users to fully control the processing method of the event, and how the ChannelHandler in Channel interacts with each other.
Each Channel in Netty has only one channelpipeline corresponding, and their compositional relationships are as follows

A Channel contains a CHANNELPIPELINE, while ChannelPipeline has maintained a two-way linked list consisting of ChannelHandlerContext, and a ChannelHandler is associated with each ChannelHandlerContext.
Read events (inbound events) and WRITE events (outbound events) In a two-way linked list, inbound events are passed from the list of HEADs to the last inbound handler, and outbound events will pass from the list TAIL to The one-stop Handler, two types of Handler interfere with each other.
From the structure, Bytebuf is constructed from a string byte array. Each byte in the array is used to store information.
Bytebuf provides two indexes, one for reading data, one for writing data. By moving in the byte array, these two indexes are positioned to locate the location where read or write information.
When read from bytebuf, its ReaderIndex will increase based on the number of bytes read.
Similarly, when writing Bytebuf, its WriterIndex will also increase according to the number of bytes written.

It should be noted that the limit is that readerIndex just reads the WriterIndex written.
When ReaderIndex exceeds WriterIndex, Netty will throw indexOutofboundsexception.
Sample code:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
public class NettyByteBuf {
public static void main(String[] args) {
// Create a BYTEBUF object, the inside of the object contains a byte array byte [10]
// divide Buffer into three areas via ReaderIndex and WriterIndex and Capacity
// The area that has been read: [0, ReaderIndex)
// Readable area: [ReaderIndex, WriterIndex)
// Well-writable area: [WriterIndex, Capacity)
ByteBuf byteBuf = Unpooled.buffer(10);
System.out.println("byteBuf=" + byteBuf);
for (int i = 0; i < 8; i++) {
byteBuf.writeByte(i);
}
System.out.println("byteBuf=" + byteBuf);
for (int i = 0; i < 5; i++) {
System.out.println(byteBuf.getByte(i));
}
System.out.println("byteBuf=" + byteBuf);
for (int i = 0; i < 5; i++) {
System.out.println(byteBuf.readByte());
}
System.out.println("byteBuf=" + byteBuf);
// Create bytebuf with UNPOOLED Tool Class
ByteBuf byteBuf2 = Unpooled.copiedBuffer("hello,xiaobai2021!", CharsetUtil.UTF_8);
// use related methods
if (byteBuf2.hasArray()) {
byte[] content = byteBuf2.array();
// convert content into string
System.out.println(new String(content, CharsetUtil.UTF_8));
System.out.println("byteBuf2=" + byteBuf2);
System.out.println(byteBuf2.getByte(0)); / / Get the ASCII code of the character H of the array 0, H = 104
int len = byteBuf2.readableBytes(); // Readable bytes 12
System.out.println("len=" + len);
// Use for to remove each byte
for (int i = 0; i < len; i++) {
System.out.println((char) byteBuf2.getByte(i));
}
// Range Read
System.out.println(byteBuf2.getCharSequence(0, 6, CharsetUtil.UTF_8));
System.out.println(byteBuf2.getCharSequence(6, 6, CharsetUtil.UTF_8));
}
}
}
The core concept in Netty isEvent loop (EventLoop), Which is actually Reactor in Reactor mode,Responsible for monitoring network events and calling event handlers for processing.In the 4.x version of ...
Zero copy hard driver - kernel buffer - protocol engine only DMA copy avoids cpu copy There was actually a cpu copy of kernel buffer - socket buffer, but the copied information can rarely be ignored; ...
Introduction to Netty Netty is a high-performance, high-scalable asynchronous event-driven network application framework, which greatly simplifies network programming such as TCP and UDP clients and s...
Why use Netty Netty is an asynchronous event-driven web application framework for rapid development of maintainable high-performance and high-profile servers and clients. Netty has the advantages of h...
Event cycle group All I / O operations in Netty are asynchronous, and the asynchronous execution results are obtained by channelfuture. Asynchronously executes a thread pool EventLoopGroup, it ...
table of Contents Thread model 1, traditional IO service model 2, Reactor mode reactor Three modes: to sum up Netty model Excommissum Thread model 1, traditional IO service model Blocked IO mode Get i...
content 1. Single Reactor single thread 2. Single Reactor Multi -thread 3. Reactor Main Strike Model Single -threaded model (single Reactor single thread) Multi -threaded model (single Reactor multi -...
Single-threaded model: the boss thread is responsible for connection and data reading and writing Hybrid model: the boss thread is responsible for connection and data reading and writing, and the work...
This chapter of the Redis database server implementations are introduced, indicating achieve Redis database-related operations, including key-value pairs in the database to add, delete, view, update a...
1、b1041 2、b1042 3、b1043 4、b1044 5、b1045...