Netty异步IO和回调函数

Netty异步IO和回调函数

在Netty中,write及writeAndFlush方法有个返回值,类型是ChannelFuture。ChannelFuture的addListener方法可以添加ChannelFutureListener监听器。ChannelFutureListener接口的抽象方法operationComplete会在write完成(无论成功或失败)时被调用,我们只需要实现这个方法即可处理一些write完成后的操作,例如write完成后关闭连接。

public class Server {
		
	public void start() throws InterruptedException {
		EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
		EventLoopGroup eventLoopGroup2 = new NioEventLoopGroup();
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(eventLoopGroup, eventLoopGroup2)
		.channel(NioServerSocketChannel.class)
		.childHandler(new ChannelInitializer() {

			@Override
			protected void initChannel(Channel arg0) throws Exception {
					ChannelPipeline pipeline = arg0.pipeline();
					pipeline.addLast(new ServerHandler());
			}
		});
		ChannelFuture future = serverBootstrap.bind(6699).sync();
		System.out.println("Server.start()");
		future.channel().closeFuture().sync();
		
		
	}
	
	
	
	public static void main(String[] args) {
				Server server = new Server();
				try {
					server.start();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	}
	
}
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf>{

	@Override
	protected void channelRead0(ChannelHandlerContext arg0, ByteBuf arg1) throws Exception {
	}

	@Override
	public void channelRead(final ChannelHandlerContext ctx, Object arg1) throws Exception {
						String string = "to C";
						ByteBuf buf = Unpooled.buffer(string.length());
						buf.writeBytes(string.getBytes());
						ChannelFuture future = ctx.writeAndFlush(buf);
						future.addListener(new ChannelFutureListener() {
							
							@Override
							public void operationComplete(ChannelFuture arg0) throws Exception {
								if(arg0.isSuccess()) { // 是否成功
									System.out.println("write操作成功");
								} else {
									System.out.println("write操作失败");
								}
								ctx.close(); // 如果需要在write后关闭连接,close应该写在operationComplete中。注意close方法的返回值也是ChannelFuture
								}
								
							
						});
	}
	
	
	
}

你可能感兴趣的:(Java学习)