public static void main(String[] args) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(eventLoopGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
// 1
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast("1", null);
ch.pipeline().addLast("2",
// 2
new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(
ChannelHandlerContext ctx,
Object msg) throws Exception {
//2.1 业务方法
ctx.write(msg);
}
});
}
});
// 3启动
try {
Channel ch = b.bind(7397).sync().channel();
ch.closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
ServerBootstrap 负责引导程序的各个组件配置,
1:group,用来设置事件循环组,
2:channel方法用来设置传输方式,一般都是NIO。还有阻塞IO,local,embbedded等方式
3:childHandler方法用来设置业务处理的类,用来处理网络传输中的输入流和输出流
ctx.write(msg);//ctx的write方法,持有输出的能力,msg代表输入流里接受到的消息
引导好程序后,通过
Channel ch = b.bind(7397).sync().channel();
ch.closeFuture().sync();
来启动程序。
最后通过
eventLoopGroup.shutdownGracefully();
来释放资源