Netty异步IO和回调函数

本文探讨了Netty框架中利用write和writeAndFlush方法进行异步IO操作时,如何通过ChannelFuture和ChannelFutureListener实现回调函数。当write操作成功或失败时,operationComplete方法会被调用,用于执行后续的连接关闭等处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<Channel>() {

			@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
								}
								
							
						});
	}
	
	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值