案例对照
在Netty中使用OIO ```java public void start() throws InterruptedException { final EchoServerHandler serverHandler = new EchoServerHandler(); // 创建EventLoopGroup EventLoopGroup group = new OioEventLoopGroup();
try {
// 创建ServerBootstrapServerBootstrap b = new ServerBootstrap();b.group(group).channel(OioServerSocketChannel.class) // 指定所使用的的OIO传输Channel.localAddress(new InetSocketAddress(port)) // 使用指定的端口设置套接字地址// 添加一个EchoServerHandler到子Channel的ChannelPipeline.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {// EchoServerHandler被标注为@Sharaable,所以我们可以总是使用同样的实例// 这里对于所有的客户端连接来说,都会使用同一个EchoServerHandler,因为其被标注为@Sharable。ch.pipeline().addLast(serverHandler);}});// 异步地绑定服务器;调用sync()方法阻塞等待知道绑定完成ChannelFuture f = b.bind().sync();// 获取Channel的CloseFuture,并且阻塞当前线程直到它完成f.channel().closeFuture().sync();
} finally {
// 关闭EventLoopGroup,释放所有资源group.shutdownGracefully().sync();
}
}
2. 将OIO传输策略修改为NIO```javapublic void start() throws InterruptedException {final EchoServerHandler serverHandler = new EchoServerHandler();// 创建EventLoopGroupEventLoopGroup group = new NioEventLoopGroup();try {// 创建ServerBootstrapServerBootstrap b = new ServerBootstrap();b.group(group).channel(NioServerSocketChannel.class) // 指定所使用的的NIO传输Channel.localAddress(new InetSocketAddress(port)) // 使用指定的端口设置套接字地址// 添加一个EchoServerHandler到子Channel的ChannelPipeline.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {// EchoServerHandler被标注为@Sharaable,所以我们可以总是使用同样的实例// 这里对于所有的客户端连接来说,都会使用同一个EchoServerHandler,因为其被标注为@Sharable。ch.pipeline().addLast(serverHandler);}});// 异步地绑定服务器;调用sync()方法阻塞等待知道绑定完成ChannelFuture f = b.bind().sync();// 获取Channel的CloseFuture,并且阻塞当前线程直到它完成f.channel().closeFuture().sync();} finally {// 关闭EventLoopGroup,释放所有资源group.shutdownGracefully().sync();}}
对比可以发现,整体的代码结构是没有变化的,唯一变化的区在在于EventLoopGroup的实现以及指定了通道创建时指定了不同的类
// 创建EventLoopGroupEventLoopGroup group = new OioEventLoopGroup();b.group(group).channel(OioServerSocketChannel.class)// 创建EventLoopGroupEventLoopGroup group = new NioEventLoopGroup();b.group(group).channel(NioServerSocketChannel.class)
