Before we begin to learn Netty, we introduce the I/O models commonly used in UNIX systems, and then briefly explain the history of Java I/O history. Introduction to Linux network I/O models
The Linux kernel operates as a file for all external devices, and the read and write operation of a file invokes the system commands provided by the kernel, returning a file descriptor (FD, filename descriptor). and read and write to a socket also has a corresponding descriptor, called Socket FD (Socket descriptor), descriptor is a number, it points to a structure in the kernel (file path, data area, etc.).
UNIX provides 5 I/O models, respectively, based on the classification of I/O models by UNIX network programming.
(1) Blocking I/O model : The most common I/O model is the blocking I/O model, by default, all file operations are blocked. We use the socket interface as an example to explain this model: Call Recvfrom in the process space, and its system call is returned until the packet arrives and is copied into the applied buffer or an error occurs, and the process waits all the time, from the call to the recvfrom to the entire period it returns. , which is called the blocking I/O model, as shown in the following illustration
(2) non-blocking I/O model : When the recvfrom from the application layer to the kernel, if the buffer does not have data, it directly returns a ewouldblock error, generally the non-blocking I/O model polling check this state to see if the kernel has data arrival, As shown in the following figure
(3) I/O multiplexing Model : Linux provides select/poll, the process passes one or more FD to a Select or poll system call, blocking on the select operation, so that select/ Poll can help us detect if multiple FD is in a ready state. Select/poll is ordered to scan for FD, and the number of supported FD is limited, so its use is subject to some constraints. Linux also provides epoll system calls, which are more performance-epoll using event-driven instead of sequential scans. When the FD is ready, the callback function rollback immediately, as shown in the following figure
(4) signal-driven I/O model : First open the socket signal driver I/O function, and through the system call Sigaction to perform a signal processing function (this system call immediately return, the process continues to work, it is non-blocking). When the data is ready, a sigio signal is generated for the process, a signal callback is used to notify the application to call Recvfrom to read the data, and the main loop function is notified to process the data, as shown in the following illustration:
(5) asynchronous I/O model : Inform the kernel to initiate an operation and let the kernel notify us after the entire operation is complete, including copying the data from the kernel to the user's own buffer area. The main difference between this model and the signal-driven model is that the signal-driven IO is informed by the kernel when we can start the next IO operation: The asynchronous I/O model informs the kernel when I/O is complete, as shown in the following illustration:
I/O multiplexing technology
During I/O programming, multithreading or I/O multiplexing technology can be used to handle multiple client access requests simultaneously. I/O multiplexing technology enables the system to handle multiple client requests simultaneously in a single thread by reusing multiple I/O blocking to the same select block. Compared with the traditional multithreaded/multi process model, I/O Multiplexing technology's biggest advantage is that the system overhead is small, the system does not need to create new additional processes or threads, do not need to maintain the operation of these processes and threads, reduce the system maintenance workload, save the system resources, I/O multiplexing main application scenario is as follows: The server needs to handle multiple sockets in a listening state or multiple connection states at the same time, and the server needs to handle multiple network protocol sockets at the same time;
Current system calls that support I/O multiplexing are Select, Pselect, poll, Epoll, and for a long time in Linux network programming, select is used for polling and network event notifications. However, some of the inherent flaws in select have caused its application to be greatly limited, and eventually Linux had to look for a select alternative in the new kernel version, eventually choosing Epoll. Epoll is similar to the principle of select, in order to overcome the shortcomings of select, Epoll made a number of significant improvements, summarized as follows: support for a process open socket descriptor (FD) unrestricted (limited to the operating system's maximum number of file handles) . I/O efficiency does not decrease linearly as the number of FD increases. Another fatal weakness of
Traditional select/poll is that when you have a large set of sockets, only a small portion of the socket is "active" due to network latency or link idle, but select/ Poll each call will scan the entire set linearly, resulting in a linear decrease in efficiency. Epoll does not have this problem, it only operates on "active" sockets-this is because in the implementation of the kernel, Epoll is implemented according to the callback function above each FD. Then only the "active" socket will go to the active call callback function, other
idle state of the socket is not. At this point, Epoll implements a pseudo aio. The uses MMAP to accelerate message delivery between the kernel and user space. The API for Epoll is simpler. Java I/O evolutionary path
From JDK1.0 to Jdk1.3,java I/O class libraries are very primitive, many UNIX network programming concepts or interfaces in the I/O class library are not reflected, such as pipe, Channel, buffer and selector. When JDK1.4 was released in 2002, NiO was officially released with the JDK as a JSR-51. It adds a Java.nio package that provides a number of APIs and class libraries for asynchronous I/O development, with the main classes and interfaces as follows: Buffer bytebuffer for asynchronous I/O operations, Pipeline pipe for asynchronous I/O operations, and various i/ o Operational (synchronous or asynchronous) Chanel, including Serversocketchanel and Socketchanel, encoding and decoding capabilities for multiple character sets, multiplexer selector for non-blocking I/O operations, file channel Filechanel;
The provision of new NiO class libraries, greatly promoted the application and development of Java based Asynchronous non-blocking programming, however, it still has imperfect place, especially to the file system processing capacity is still insufficient, the main problem is as follows: There is no uniform file attributes (such as read and Write permissions), the API is weak, For example, the cascading creation and recursive traversal of a directory often needs to be implemented by itself; Some advanced APIs for the underlying storage system are not available; All file operations are synchronous blocking calls, and asynchronous file read and write operations are not supported.
July 28, 2011, JDK7 officially released. One of its big highlights is the upgrading of the original NiO class library, known as NIO 2.0. NIO 2.0 evolved from JSR-203, which provides the following three improvements: APIs that provide the ability to bulk obtain file properties that are platform-independent and not coupled to specific file systems. In addition, it provides a standard file of SPI for each service provider to extend the implementation, provides AIO functionality, supports file-based asynchronous I/O operations and asynchronous operations against network sockets, and completes JSR-51-defined channel functionality, including support for configuration and multicast datagrams. Netty4 Entry Application
Development environment Idea JDK 1.7 maven 3.3 1, adding maven dependencies
<!--Netty-->
<dependency>
<groupId>io.netty</groupId>
<artifactId> netty-all</artifactid>
<version>4.1.6.Final</version>
</dependency>
2, Netty service end development
Package com.bytebeats.netty4.sample.ch1;
Import com.bytebeats.netty4.sample.util.Constants;
Import Io.netty.bootstrap.ServerBootstrap;
Import io.netty.channel.*;
Import Io.netty.channel.nio.NioEventLoopGroup;
Import Io.netty.channel.socket.SocketChannel;
Import Io.netty.channel.socket.nio.NioServerSocketChannel;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
/** * Hello World Server.
* @author Ricky * * */public class Echoserver {private Logger Logger = Loggerfactory.getlogger (GetClass ());
private int port;
public echoserver (int port) {this.port = port; public void Run () throws Exception {Eventloopgroup bossgroup = new Nioeventloopgroup ();//(1) Eve
Ntloopgroup Workergroup = new Nioeventloopgroup ();
try {serverbootstrap b = new Serverbootstrap ();//(2) B.group (Bossgroup, Workergroup) . Channel (Nioserversocketchannel.class)//(3) option (Channeloption.so_backlog, 1024). Childhandler (New channelinitializer<socketchannel> () {//(4) @Override public void Initchannel (Socketchannel ch) throws Exception {Channelpipeline p = ch.pipeline (
);
P.addlast (New Echoserverhandler ());
}
});
Bind and start to accept incoming connections. Channelfuture f = b.bind (port). sync ();
(7) Logger.info ("Server Bind port:{}", port);
Wait until the "server socket is closed."
F.channel (). Closefuture (). sync ();
Finally {//Shut down the all event loops to terminate all threads.
Bossgroup.shutdowngracefully ();
Workergroup.shutdowngracefully ();
} public static void Main (string[] args) throws Exception {new Echoserver (Constants.port). Run ();
}
}
Package com.bytebeats.netty4.sample.ch1;
Import Io.netty.buffer.ByteBuf;
Import io.netty.buffer.Unpooled;
Import Io.netty.channel.ChannelHandlerContext;
Import Io.netty.channel.ChannelInboundHandlerAdapter;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
/** * Handles a server-side channel. * * public class Echoserverhandler extends Channelinboundhandleradapter {//(1) Private Logger Logger = loggerfactory.
GetLogger (GetClass ()); @Override public void Channelread (Channelhandlercontext ctx, Object msg) {//(2) logger.info ("Server channel
Read ... ");
Bytebuf buf = (bytebuf) msg;
byte[] req = new byte[buf.readablebytes ()];
Buf.readbytes (req);
try {string BODY = new String (req, "UTF-8");
Logger.info ("Server channel Read msg:{}", body);
}catch (Exception e) {e.printstacktrace ();
String response = "Hello from server"; Bytebuf resp = Unpooled.copiedbuffer (Response.getbytes ());
Ctx.write (RESP); @Override public void Channelreadcomplete (Channelhandlercontext ctx) throws Exception {logger.info ("se
RVer Channel read complete ");
Ctx.flush (); @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {//(4)//Close the
Connection when a exception is raised.
Logger.error ("Server caught Exception", cause);
Ctx.close (); }
} 3, Netty Client development
Package com.bytebeats.netty4.sample.ch1;
Import com.bytebeats.netty4.sample.util.Constants;
Import Io.netty.bootstrap.Bootstrap;
Import io.netty.channel.*;
Import Io.netty.channel.nio.NioEventLoopGroup;
Import Io.netty.channel.socket.SocketChannel;
Import Io.netty.channel.socket.nio.NioSocketChannel;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
/** * Hello World Client.
* @author Ricky * * */public class Echoclient {private Logger Logger = Loggerfactory.getlogger (GetClass ());
Private String host;
private int port;
Public Echoclient (String host, int port) {this.host = host;
This.port = port;
public void Send () throws interruptedexception {Eventloopgroup group = new Nioeventloopgroup ();
try {Bootstrap b = new Bootstrap ();
B.group (Group). Channel (niosocketchannel.class). Option (Channeloption.tcp_nodelay, True) . Handler (New CHANNELINITIALIZER<SOCKetchannel> () {@Override protected void Initchannel (Socketchannel ch) throws Exception
{Channelpipeline p = ch.pipeline ();
P.addlast (New Echoclienthandler ());
}
});
Start the client.
Channelfuture f = b.connect (host, port). sync ();
Logger.info ("Client Connect to host:{}, port:{}", host, Port);
Wait until the connection is closed.
F.channel (). Closefuture (). sync ();
Finally {//Shut down the event loop to terminate all threads.
Group.shutdowngracefully (); } public static void Main (string[] args) throws Exception {new Echoclient (Constants.host, CONSTANTS.P
ORT). Send ();
}
}
Package com.bytebeats.netty4.sample.ch1;
Import Io.netty.buffer.ByteBuf;
Import io.netty.buffer.Unpooled;
Import Io.netty.channel.ChannelHandlerContext;
Import Io.netty.channel.ChannelInboundHandlerAdapter;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
/** * Handles a client-side channel. * * public class Echoclienthandler extends Channelinboundhandleradapter {//(1) Private Logger Logger = loggerfactory.
GetLogger (GetClass ());
Private final Bytebuf Firstmessage;
Public Echoclienthandler () {byte[] req = ' Hello from client '. GetBytes ();
Firstmessage = Unpooled.buffer (req.length);
Firstmessage.writebytes (req); @Override public void channelactive (Channelhandlercontext ctx) throws Exception {Logger.info ("Client C
Hannel active ");
Send the message to Server logger.info ("Client send req ...");
Ctx.writeandflush (Firstmessage); @Override public void Channelread (ChannelhandlercontexT ctx, Object msg) {//(2) bytebuf buf = (bytebuf) msg;
byte[] req = new byte[buf.readablebytes ()];
Buf.readbytes (req);
try {string BODY = new String (req, "UTF-8");
Logger.info ("Client channel Read msg:{}", body);
}catch (Exception e) {e.printstacktrace (); @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {//(4)//Clo
Se the connection when a exception is raised.
Logger.error ("Client caught exception", cause);
Ctx.close (); }
}
Source has been uploaded to Github:https://github.com/tifg/netty4-samples