NOTE

Component Introduction

1. What it is 2. Components 3. Processing flow 4. ChannelPipeline

JavaCreated Updated 2 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What It Is

An asynchronous event-driven network framework. Its APIs are much easier to use than Java’s native BIO and NIO APIs, and Netty can freely switch between NIO and BIO implementations.

2. Components

2.1. Bootstrap

Used to start Netty. It includes work such as creating threads and creating sockets.

2.2. EventLoop

An infinite loop that continuously listens for new events. When a new event arrives, it passes the event to a ChannelHandler for processing.

2.3. EventLoopGroup

A collection of EventLoop instances.

2.4. SocketChannel

Represents a TCP socket connection. It is managed by the same EventLoop, and an EventLoop is single-threaded, so operations inside this SocketChannel are single-threaded and there is no need to worry about concurrency issues.

2.5. ChannelInitializer

A special ChannelHandler. It is called when a SocketChannel is instantiated. After the SocketChannel is initialized, this handler is removed from the ChannelPipeline.

2.6. ChannelPipeline

Every SocketChannel has a ChannelPipeline: a list containing a group of ChannelHandler instances.

2.7. ChannelHandler

Processes data in a SocketChannel.

3. Processing Flow

First use Bootstrap to start Netty and initialize resources such as threads.

Then use an EventLoop to listen for various events on a SocketChannel.

When an event occurs on the SocketChannel, it is handed to the ChannelHandler instances in the ChannelPipeline associated with that SocketChannel. For example, when a SocketChannel is created it is handled by ChannelInitializer; when reading from or writing to the SocketChannel, it is handled by the ChannelHandler instances in the ChannelPipeline.

4. ChannelPipeline

ChannelHandler has two subinterfaces: ChannelInboundHandler and ChannelOutboundHandler. The former is responsible for reading data from the SocketChannel into the application, while the latter writes application data out to the SocketChannel.

ChannelHandler instances can be viewed as a chain of calls. For example, Handler1 converts raw bytes into an HTTP Object (Codecs), while Handler2 converts the HTTP Object into another type of Object.

ChannelInboundHandler and ChannelOutboundHandler are actually in the same list. Data can be processed in a ChannelInboundHandler and then written directly back through a ChannelOutboundHandler, as shown below.

4.1. Codecs

Special ChannelHandler implementations used to convert message formats.

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub