首页  

netty ChannelFuture 实例     所属分类 netty 浏览量 1926
netty   基于事件 异步
一般操作都会异步返回 ,除非 调用 同步阻塞方法 sync()

		Bootstrap bootstrap = new Bootstrap();
		ChannelFuture future = bootstrap.group(new NioEventLoopGroup())
		.channel(NioSocketChannel.class)
		// 空的 handler
		.handler(new ChannelInboundHandlerAdapter())
		.remoteAddress("127.0.0.1", 6789).connect();
		
		// 同步阻塞
		// future.sync();
		
		// future=AbstractBootstrap$PendingRegistrationPromise@4cc0edeb(incomplete)

		System.out.println("future="+future+"\n\n");
		
		future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
            	// future=AbstractBootstrap$PendingRegistrationPromise@4cc0edeb(success)
            	// future=AbstractBootstrap$PendingRegistrationPromise@4cc0edeb(failure: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /127.0.0.1:6789)
        		System.out.println("future="+future+"\n\n");
                if (future.isSuccess()) {
                    ByteBuf buffer = Unpooled.copiedBuffer("hello \n", Charset.defaultCharset());
                    // 写完消息之后 关闭 channel 
                    ChannelFuture wf = future.channel().writeAndFlush(buffer).addListener(ChannelFutureListener.CLOSE);
                } else {
                    Throwable cause = future.cause();
                    cause.printStackTrace();
                }
            }
        });		
	}
	
	
connect 操作 立即返回  ChannelFuture
调用 ChannelFuture 的 sync 方法 同步阻塞
添加监听器 , connect 操作完成(成功或失败) 通知处理

ChannelFutureListener    
void operationComplete(F future) throws Exception;

ChannelFuture
boolean isSuccess();

	

ChannelFutureListener.CLOSE ChannelFutureListener.CLOSE_ON_FAILURE public interface ChannelFutureListener extends GenericFutureListener< ChannelFuture> { ChannelFutureListener CLOSE = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { future.channel().close(); } }; ChannelFutureListener CLOSE_ON_FAILURE = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { future.channel().close(); } } }; 完整代码 https://gitee.com/dyyx/netty4demo/blob/master/src/main/java/dyyx/test/ConnectionTest.java

上一篇     下一篇
netty空闲连接检测

netty 服务端启动日志

springboot应用安全防护

netty异常处理机制

Garbage Collection Roots

内存分析工具MAT中的重要概念