What is Netty ?
Netty is an open source Java NIO framework which can be used to develop network related applications.In this tutuorial I am going to exaplain basic architecture of the netty and how it is used to develop basic appilcations.
Netty Concepts
- Bootstraps
Bootstrapping is used to create netty channels which is used to handle incoming and outgoing connections and events through it. Basically inbound side consists of ServerBootstrap. ServerBootstrap is used to configure and create channels (TCP , HTTP .. etc) for incoming client connections. ServerBootstrap is extended from Bootstrap which can be used to configure client Bootstrap as well. Client Bootstrap is used to make connections with backend servers.
example :-
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(4);
try {
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_BACKLOG, 1024);
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ServerInitializer());
Channel ch = b.bind(PORT).sync().channel();
System.err.println("Open your web browser and navigate to " +
(SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
Here we are creating ServerBootstrap and configure with transport level parameters. You can see that it has given with two eventloop groups called master and worker. It is explained in the following sections. Basically it used for handle incoming connections.
- EventLoop and EventLoopGroup
EventLoop is like a Java thread which is used to handle connections. There are varoiuse EventLoop implementations in netty such NioEventLoop , UDPDatagramEventLoop .. etc. EventLoopGroup is a collection of Event Loops. Basically we can define how many Event Loops should be included in the EventLoopGroup when it is creating. When creating ServerBootstrap we have given that Master and Worker EventLoopGroups. Master EventLoopGroup is responsible for accepting incoming connections and Worker EventLoopGroup is responsible for handling IO operations of the accepted connections.Each accepted connection is bound to particular Worker EventLoop for its life time.
- Channel and ChannelHandlerContext
Netty channel is a representation of an accepted connection.Netty channel is bound to a one particular EventLoop for it is life time. For each channel netty creates a channel pipeline and I will discuss it in the following sections. we can save attributes in channel which can be retrieved in later calls of the channel. ChannelHandlerContext is unique for each handler in the pipeline. handler concept also describes in later part of this tutorial.
- Channel Handlers
Basically netty has Inbound and Outbound handlers. Inbound handlers are executed when IO events are read from socket to application and Outbound handlers are executed when IO events are written from application to socket. Netty Handlers can be shared with netty pipelines but the recommended approach is not share handlers .Handler has a specific logic to do some applications specific logic with incoming messages it can be a byte to message conversion , message to message conversion or message to byte conversion. There can be multiple handlers executed inside a netty pipeline.
- Netty Pipeline
Pipeline is a representation of a message flow of particular accepted connection. Handlers can be integrated into pipeline and for each connection it creates a pipeline. All the handlers in pipeline are thread safe instead if handler is shared. Following is the sample code for pipeline creation.
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpServerCodec());
p.addLast(new ServerHandler());
}
}
Handlers in the pipeline are executed according to the integrated positions in the pipeline. But in Inbound path Inbound Handlers are only executed accordingly and in Outbound direction Outbound Handlers are executed.
- Important Facts
Do not block the handler execution throughout the handler implementation code. If handler is got blocked, the underlying Event Loop which is executing that pipeline will be blocked. So it will affect the IO WorkerPool of netty to be get overloaded and ultimate connection processing will be delayed.
You can execute Netty Handler in a separate WorkerPool by providing executorservice when adding it to the channel pipeline as follows.
p.addLast(“executorservice” ,new ServerHandler());