What is a Netty? Netty is a framework. Or a toolset. Encapsulates the Java API for network programming.

What are the core components of Netty?

  1. Channel: A basic construct of Java NIO that represents an open connection to an entity (hardware device, file, network socket, etc.). Used as incoming (inbound) or outgoing (outbound) data

  2. Callback: A way to encapsulate what needs to be done after the operation is complete

  3. Future: Provides access to the results of asynchronous operations

  4. Events and ChannelHandler: Things that happen during program execution are abstracted (events) and handled by a ChannerHandler, which is similar to a callback that is executed in response to a particular event

Netty的Hello world

server

public class EchoServer { private final int port; public EchoServer(int port) { this.port = port; } public static void main(String[]args)throws Exception{ new EchoServer(8888).start(); } public void start() throws Exception{ final EchoServerHandler handler = new EchoServerHandler(); EventLoopGroup group = new NioEventLoopGroup(); try{ ServerBootstrap b = new ServerBootstrap(); b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(handler); }}); ChannelFuture f = b.bind().sync(); f.channel().closeFuture().sync(); }finally { group.shutdownGracefully().sync(); }}}Copy the code

serverHandler

public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        System.out.printf("Server get:"+in.toString(CharsetUtil.UTF_8)); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // Flush the message currently temporarily stored in the ChannelOutboundBuffer to the remote channel on the next flush or writeAndFlush and close the channel ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); }}Copy the code

client

public class EchoClient { private final String host; private final int port; public EchoClient(String host,int port){ this.host=host; this.port=port; } public void start() throws Exception{ EventLoopGroup group = new NioEventLoopGroup(); try{ Bootstrap b = new Bootstrap(); B.group (group).channel(niosocketchannel.class)// specify the NIO transport mode. RemoteAddress (new InetSocketAddress(host,port))// specify the remoteAddress Handler (new ChannelInitializer<SocketChannel>() {// Add handler @override protected void to channel pipeline initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoClientHandler()); //channelHander to pipeline}}); ChannelFuture f = b.connect().sync(); // Connect to the remote node, block until connection is complete system.out.println ("wait"); f.channel().closeFuture().sync(); // block until connection is closed system.out.println ("over");
        }finally {
            System.out.println("shutdown"); group.shutdownGracefully().sync(); }} public static void main(String[]args) throws Exception{new EchoClient("localhost",8888).start(); }}Copy the code

clientHandler

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello world",CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("Client get:"+msg.toString(CharsetUtil.UTF_8)); }}Copy the code

Channel, Eventloop, ChannelFuture

They are Netty’s abstract components of the network.

The Channel itself is used to provide basic IO operations (bind/connect/read/write), and the EventLoop handles what happens once the connection is established. Each channel can have only one EventLoop, but one EventLoop corresponds to multiple channels. An EventLoop is bound to only one Thread during its lifetime, and all IO operations in a Channel are performed in one Thread. The results of the execution are retrieved through ChannelFuture

What are the characteristics of a Channel?

  1. Channel is the core of the transmission apis, each was assigned a ChannelPipeline and ChannelConfig ChannelConfig contains all the configuration of the channel, and support the hot update
  2. Each channel is unique and the order between channels is compared using Comparable
  3. The implementation of a channel is thread-safe

What is the relationship between pipeline and handler?

Pipelines manage data streams, and handlers (clients and servers) handle logic.

The ChannelHandler receives the event, processes it logically, and passes the data to the next ChannelHandler in the chain (multiple ChannelHandlers defined in some order). ChannelPipLine is the order in which the ChannelHandler is marshaled (the relationship is established when the ChannelPipLine assembles its own ChannelHandler when the ChannelInitializer executes its initChannel). ChannelHandler provides adaptive implementation classes for convenience to let users focus on their own business logic.

What is a bootstrap?

There are two types, client (BootStrap for short) and server (ServerBootStrap for short). There are two differences

  1. BootStrap is used to connect remote nodes, and ServerBootStrap is used to bind local ports to listen for connections
  2. The client needs an EventLoopGroup (something to hold multiple EventLoops), the server needs two (possibly the same instance), one to bind to the local port to indicate that it has listened (allocate an EventLoop), and one to handle the client connection (allocate an EventLoop).

What transport types are supported by Netty?

  • NIO: Implementation of selector mechanism based on Java API. The general principle is: when the channel state changes, it will be notified, and the task corresponding to the state change will be executed. After the response, the selector will be reset, and the process will be repeated again

  • Epoll: Can only be used on Linux systems and performs better than the JDK’s NIO under high loads. The general principle is: I/O multiplexing (manage multiple file descriptors with one file character), when a file descriptor is readable or writable, it is notified and executed immediately.
  • OIO(old blocking IO) : Java.net-based blocking IO. The idea is that a single thread listens on a socket, and any I/O operation can be blocked at any point in time
  • Local: Communication between clients and servers running on the same JVM
  • Embedded: Uses a channel but does not require a true network transmission. Embedded is used for testing

The appendix

Netty In Action