packagecom.netty5.server;importjava.net.InetSocketAddress;importio.netty.bootstrap.ServerBootstrap;importio.netty.channel.Channel;importio.netty.channel.ChannelFuture;importio.netty.channel.ChannelHandlerContext;importio.netty.channel.ChannelInitializer;importio.netty.channel.ChannelOption;importio.netty.channel.EventLoopGroup;importio.netty.channel.SimpleChannelInboundHandler;importio.netty.channel.nio.NioEventLoopGroup;importio.netty.channel.socket.nio.NioServerSocketChannel;importio.netty.handler.codec.string.StringDecoder;importio.netty.handler.codec.string.StringEncoder;/***@authorChalmers 2016年2月20日 下午7:52:49*/
public classNettyServer2 {public static voidmain(String[] args) {//得到ServerBootstrap对象
ServerBootstrap serverBootstrap = newServerBootstrap();//创建线程池
EventLoopGroup boss = newNioEventLoopGroup();
EventLoopGroup worker= newNioEventLoopGroup();try{//类似于Netty3中的工厂
serverBootstrap.group(boss, worker);
serverBootstrap.channel(NioServerSocketChannel.class);//类似于Netty3中的管道
serverBootstrap.childHandler(new ChannelInitializer() {
@Overrideprotected void initChannel(Channel channel) throwsException {/*** 将“上传下载”数据装饰成String类型*/channel.pipeline().addLast(newStringDecoder());
channel.pipeline().addLast(newStringEncoder());//要处理的Handler
channel.pipeline().addLast(newServerHandler2());
}
});//设置参数,TCP参数
serverBootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的设置,链接缓冲池的大小
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的设置,维持链接的活跃,清除死链接
serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的设置,关闭延迟发送//绑定端口,并且返回ChannelFuture对象
ChannelFuture future = serverBootstrap.bind(newInetSocketAddress(9090));
System.out.println("启动服务器...");//等待客户端的关闭
Channel channel =future.channel();//要记得是closeFuture(),作用是等待服务端的关闭
channel.closeFuture().sync();//该条语句不会输出,原因:上面没有关闭...//System.out.println("客户端已经关闭...");
} catch(Exception e) {
e.printStackTrace();
}finally{
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}class ServerHandler2 extends SimpleChannelInboundHandler{
@Overrideprotected voidmessageReceived(ChannelHandlerContext arg0, String arg1)throwsException {//输出接收到的数据
System.out.println(arg1);//向客户端发送数据
arg0.channel().writeAndFlush("hi");
}/****/@Overridepublic void channelActive(ChannelHandlerContext ctx) throwsException {super.channelActive(ctx);
System.out.println("channelActive");
}
@Overridepublic void channelInactive(ChannelHandlerContext ctx) throwsException {super.channelInactive(ctx);
System.out.println("channelInactive");
}
}