目前基于推荐版的4.1.12.Final在学习过程中,可能会出现个别接口不一致的情况。所以记录可在4.1.12下编译通过的代码
package net.xjdsz.n;import io.netty.bootstrap.ServerBootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import java.util.Date;/*** Created by dingshuo on 2017/6/14.*/public class TimeServer {public void bind(int port) throws Exception{EventLoopGroup bossGroup=new NioEventLoopGroup();EventLoopGroup workerGroup=new NioEventLoopGroup();try{ServerBootstrap b=new ServerBootstrap();b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,1024).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf=(ByteBuf)msg;byte[] req=new byte[buf.readableBytes()];buf.readBytes(req);String body=new String(req,"UTF-8");System.out.println("收到数据:"+body);String currentTime=new Date(System.currentTimeMillis()).toString();ByteBuf resp= Unpooled.copiedBuffer(currentTime.getBytes());ctx.write(resp);}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}});}});//绑定端口,同步等待成功ChannelFuture f=b.bind(port).sync();//等待服务端监听端口关闭f.channel().closeFuture().sync();}finally {//退出,释放资源bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception{TimeServer timeServer=new TimeServer();timeServer.bind(2000);}}