前言
Netty的IO操作是异步的,如何判断当前操作是否成功还是失败呢,这就需要配置监听器了。
在服务端绑定端口时,绑定操作是异步操作,会立即返回ChannelFuture ,可通过future来获取操作状态。
ChannelFuture常用操作:
- isDone:判断操作是否执行完成
- isSuccess:判断操作是否执行成功
- isCancelled:判断操作是否被取消
- cause:获取操作失败的原因
案例1:监听绑定端口
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
Map<Integer, SocketChannel> map = new ConcurrentHashMap<>();
try {
//服务端创建的是ServerBootstrap
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(io.netty.channel.socket.SocketChannel socketChannel) throws Exception {
map.put(socketChannel.hashCode(), socketChannel);
socketChannel.pipeline().addLast(new ServerHandler(map));
}
})
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = bootstrap.bind(9527).sync().addListener(future1 -> {
if (future1.isSuccess()) {
System.out.println("端口绑定成功");
} else {
System.out.println("端口绑定失败");
}
if (future1.isDone()) {
System.out.println("端口绑定任务执行完成");
} else {
System.out.println("端口绑定任务执行失败");
}
});
future.channel().closeFuture().sync();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
案例1:监听发送消息
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ChannelFuture future = ctx.channel().writeAndFlush(Unpooled.copiedBuffer("hello 客户端", CharsetUtil.UTF_8)).addListener(future1 -> {
if (future1.isSuccess()) {
System.out.println("消息发送成功");
} else {
System.out.println("消息发送失败");
}
if (future1.isDone()) {
System.out.println("消息发送任务执行完成");
} else {
System.out.println("消息发送任务执行失败");
}
} );
}
事件完成后,可根据监听器回调结果进行后续业务处理,比如修改推送消息的状态,是否成功推送?