NIO network programming framework Netty

1. Introduction of Netty

Netty. IO/Netty. IO/Netty

Netty is an asynchronous event-driven network application framework for rapid development of maintainable high-performance servers and clients.

Netty is a NIO client-server framework that enables fast and easy development of network applications, such as servers and clients. It greatly simplifies network programming such as TCP and UDP socket servers.

“Fast and easy” does not mean that the generated application will suffer from maintainability or performance issues. Netty is well designed and has accumulated experience implementing many protocols (such as FTP, SMTP, HTTP), as well as various binary and text-based legacy protocols. As a result, Netty managed to find a way to achieve ease of development, performance, stability, and flexibility without compromising.

2. Who is using Netty

Large open source projects such as Dubbo, Zookeeper, RocketMQ, ElasticSearch, Spring5(an implementation of the HTTP protocol), GRpc, and Spark all use Netty as the underlying communication framework.

3. Core concepts in Netty

1) Channel

Pipes, which encapsulate sockets, contain a set of apis that greatly simplify the complexity of operating directly with sockets.

2) EventLoopGroup

An EventLoopGroup is a pool of eventloops that contains many eventloops.

Netty assigns an EventLoop to each Channel, which handles all events such as user connection requests and processing of user requests. EventLoop itself is just a thread-driver that binds only one thread to handle all I/O events for a Channel during its lifetime.

Once a Channel is bound to an EventLoop, it cannot be changed for the lifetime of the Channel. An EventLoop can bind to multiple channels. That is, the relationship between Channel and EventLoop is N :1, while the relationship between EventLoop and thread is 1:1.

3) ServerBootStrap

Used to configure the entire Netty code to associate the components. The server uses ServerBootStrap and the client uses BootStrap.

4) ChannelHandler and ChannelPipeline

Channelhandlers are the handlers for the data in a Channel. These handlers can be either system-defined codecs or user-defined ones. These handlers are added to a ChannelPipeline object, and the data in the Channel is processed in the order they are added.

5) ChannelFuture

All I/O operations in Netty are asynchronous, that is, operations do not return results immediately. Therefore, Netty defines a ChannelFuture object to represent the asynchronous operation. If you want to get the return value of the asynchronous operation, you can add a listener to the asynchronous operation by using the addListener() method of the asynchronous operation object, registering a callback for the asynchronous operation: execute it immediately after the result comes in. Netty’s asynchronous programming model is built on the concepts of futures and callbacks.

4. Netty execution process