学习 Netty(二):初识 Netty

Netty 简介

Netty 是一个异步事件驱动的网络应用框架,用于可维护的高性能协议服务端和客户端的快速开发。

netty

官网:https://netty.io/

第一个 Netty 应用

EchoServer.java

public class EchoServer {

    public static void main(String[] args) throws Exception {
        new EchoServer(8421).start();
    }

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup(); // ①
        try {
            ServerBootstrap bootstrap = new ServerBootstrap(); // ②
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(this.port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new EchoClientHandler()); // ③
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}

EchoClientHandler.java

@Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("Get it!", CharsetUtil.UTF_8));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
        System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));
    }
}

参考:

  • 《Netty 实战》 人民邮电出版社