PDF
1Netty(1)Contents .................................................................................................... 1 ............................................................................................... 2使ChannelEventLoop线ChannelFutureECHO serverpublic class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // handlermsg( // release msgwriteAndFlush ctx.writeAndFlush(msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); }}ServiceBootStrappublic class EchoServer { private final int port; 2 public EchoServer(int port) { this.port = port; } public void run() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = bootstrap.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { new EchoServer(9999).run(); }}EventLoopServer ChannelChannelChannelPipelineChannelInitializerChannelHandlerChannelPipeline 3ChannelHandlerByteToMessageDecoderProtobufEncoderSimpleChannelInboundHandler<T>void channelRead0(ChannelHandlerContext ctx, I msg)Bootstrap使ServerBootstrap使BootstrapEventLoopGroup

HTML view coming soon.

Download PDF for the full formatted version.