Netty异步IO和回调函数

来源:互联网 发布:w7内外网转换软件 编辑:程序博客网 时间:2024/06/06 00:36

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>() {@Overrideprotected 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 blocke.printStackTrace();}}}
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf>{@Overrideprotected void channelRead0(ChannelHandlerContext arg0, ByteBuf arg1) throws Exception {}@Overridepublic 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() {@Overridepublic 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}});}}
原创粉丝点击