Make it Better
Netty5例子
2016-9-24 StanWind


//服务类



ServerBootstrap bootstrap = new ServerBootstrap();







//Boss  Work



NioEventLoopGroup boss = new NioEventLoopGroup();



NioEventLoopGroup work = new NioEventLoopGroup();



try {



//设置线程



bootstrap.group(boss, work);



//设置socket工厂



bootstrap.channel(NioServerSocketChannel.class);



//设置pipe工厂



bootstrap.childHandler(new ChannelInitializer<Channel>() {



protected void initChannel(Channel ch) throws Exception {



ch.pipeline().addLast(new StringDecoder());



ch.pipeline().addLast(new StringEncoder());



ch.pipeline().addLast(new ServerHandler());



};



});



//设置参数



bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketChannel的设置 连接缓冲池 最大等待连接数 2048







//SocketChannel设置



bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//自动关闭连接 维持链接活跃 清除死链接



bootstrap.childOption(ChannelOption.TCP_NODELAY, true);







ChannelFuture future = bootstrap.bind(new InetSocketAddress(7000));



System.out.println("start");



//等待channel关闭 



future.channel().closeFuture().sync();



System.out.println("sync");



} catch (InterruptedException e) {



// TODO Auto-generated catch block



e.printStackTrace();



}finally{



System.out.println("finally");



//释放资源



boss.shutdownGracefully();



work.shutdownGracefully();



}







}

发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容