原文链接
Channel Pipeline API to build chain of handlers
To perform read and write, Netty provides you Channel Handlers , inbound & outbound. When there is something to read, Channel Inbound Handlers are invoked and when there is something to write, Channel Outbound Handlers are invoked.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class SimpleNettyServerBootstrap { void start (int port) throws InterruptedException { Utils.log("Starting server at: " + port); EventLoopGroup bossGroup = new NioEventLoopGroup (); EventLoopGroup workerGroup = new NioEventLoopGroup (); try { ServerBootstrap b = new ServerBootstrap (); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new SimpleTCPChannelInitializer ()) .childOption(ChannelOption.SO_KEEPALIVE, true ); ChannelFuture f = b.bind(port).sync(); if (f.isSuccess()) Utils.log("Server started successfully" ); f.channel().closeFuture().sync(); } finally { Utils.log("Stopping server" ); workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class SimpleTCPChannelHandler extends SimpleChannelInboundHandler <String> { @Override public void channelActive (ChannelHandlerContext ctx) { Utils.log(ctx.channel().remoteAddress(), "Channel Active" ); } @Override protected void channelRead0 (ChannelHandlerContext ctx, String s) throws Exception { Utils.log(ctx.channel().remoteAddress(), s); ctx.channel().writeAndFlush("Thanks\n" ); } @Override public void channelInactive (ChannelHandlerContext ctx) { Utils.log(ctx.channel().remoteAddress(), "Channel Inactive" ); } }
Tcp非全双工的,You can’t directly send or receive objects over TCP channel. You have to convert from bytes to object while reading and from objects to bytes while writing?