io.netty.channel.ChannelFuture Java Examples

The following examples show how to use io.netty.channel.ChannelFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Netty4HttpServerTransport.java    From crate with Apache License 2.0 6 votes vote down vote up
private TransportAddress bindAddress(final InetAddress hostAddress) {
    final AtomicReference<Exception> lastException = new AtomicReference<>();
    final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
    boolean success = port.iterate(portNumber -> {
        try {
            synchronized (serverChannels) {
                ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)).sync();
                serverChannels.add(future.channel());
                boundSocket.set((InetSocketAddress) future.channel().localAddress());
            }
        } catch (Exception e) {
            lastException.set(e);
            return false;
        }
        return true;
    });
    if (!success) {
        throw new BindHttpException("Failed to bind to [" + port.getPortRangeString() + "]", lastException.get());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Bound http to address {{}}", NetworkAddress.format(boundSocket.get()));
    }
    return new TransportAddress(boundSocket.get());
}
 
Example #2
Source File: LispControllerBootstrap.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Stitches all channel handlers into server bootstrap.
 */
private void run() {

    try {
        final Bootstrap bootstrap = createServerBootstrap();

        configBootstrapOptions(bootstrap);

        lispPorts.forEach(p -> {
            InetSocketAddress sa = new InetSocketAddress(p);
            channelFutures.add(bootstrap.bind(sa));
            log.info("Listening for LISP router connections on {}", sa);
        });

        for (ChannelFuture f : channelFutures) {
            f.sync();
        }

    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
 
Example #3
Source File: EchoServerV4.java    From netty.book.kor with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoServerV4FirstHandler());
                p.addLast(new EchoServerV4SecondHandler());
            }
        });

        ChannelFuture f = b.bind(8888).sync();
        f.channel().closeFuture().sync();
    }
    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example #4
Source File: HexDumpProxyFrontendHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    if (outboundChannel.isActive()) {
        outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // was able to flush out data, start to read the next chunk
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    }
}
 
Example #5
Source File: HttpClient.java    From Jantent with MIT License 6 votes vote down vote up
public void start() throws Exception{
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new HttpClientInitializer());

        // 发起异步连接
        ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 3560));
        // 当客户端链路关闭
        future.channel().closeFuture().sync();
    }finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
 
Example #6
Source File: AddPathBasePathsTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    final TablesKey tk = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
    final Map<TablesKey, PathSelectionMode> pathTables = ImmutableMap.of(tk,
        BasePathSelectionModeFactory.createBestPathSelectionStrategy());

    this.ribImpl = new RIBImpl(this.tableRegistry, new RibId("test-rib"), AS_NUMBER, new BgpId(RIB_ID),
            this.ribExtension,
            this.serverDispatcher, this.codecsRegistry, getDomBroker(), getDataBroker(), this.policies,
            TABLES_TYPE, pathTables);
    this.ribImpl.instantiateServiceInstance();
    final ChannelFuture channelFuture = this.serverDispatcher.createServer(
        new InetSocketAddress(RIB_ID, PORT.toJava()));
    waitFutureSuccess(channelFuture);
    this.serverChannel = channelFuture.channel();
}
 
Example #7
Source File: ClientHttp2ObjectEncoder.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture doWriteHeaders(int id, int streamId, RequestHeaders headers, boolean endStream) {
    final Http2Connection conn = encoder().connection();
    if (isStreamPresentAndWritable(streamId)) {
        if (keepAliveHandler != null) {
            keepAliveHandler.onReadOrWrite();
        }
        return encoder().writeHeaders(ctx(), streamId, convertHeaders(headers), 0,
                                      endStream, ctx().newPromise());
    }

    final Endpoint<Http2LocalFlowController> local = conn.local();
    if (local.mayHaveCreatedStream(streamId)) {
        final ClosedStreamException closedStreamException =
                new ClosedStreamException("Cannot create a new stream. streamId: " + streamId +
                                          ", lastStreamCreated: " + local.lastStreamCreated());
        return newFailedFuture(UnprocessedRequestException.of(closedStreamException));
    }

    // Client starts a new stream.
    return encoder().writeHeaders(ctx(), streamId, convertHeaders(headers), 0, endStream,
                                  ctx().newPromise());
}
 
Example #8
Source File: DFSocketManager.java    From dfactor with MIT License 6 votes vote down vote up
protected ChannelFuture doTcpConntecSync(DFTcpClientCfg cfg, EventLoopGroup ioGroup, ChannelHandler handler){
	if(ioGroup == null){
		return null;
	}
	Bootstrap boot = new Bootstrap();
	boot.group(ioGroup)
		.option(ChannelOption.ALLOCATOR, 
				PooledByteBufAllocator.DEFAULT)
		.option(ChannelOption.SO_KEEPALIVE, cfg.isKeepAlive())
		.option(ChannelOption.SO_RCVBUF, cfg.getSoRecvBufLen())
		.option(ChannelOption.SO_SNDBUF, cfg.getSoSendBufLen())
		.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int)cfg.getConnTimeout())
		.option(ChannelOption.TCP_NODELAY, cfg.isTcpNoDelay())
		.handler(new TcpHandlerInit(false, cfg.getTcpProtocol(), 
				cfg.getTcpMsgMaxLength(), 0, 0, cfg.getWsUri(), null, 
				cfg.getDecoder(), cfg.getEncoder(), cfg.getUserHandler(), cfg.getSslCfg()
				, cfg.getReqData(), handler));
	if(ioGroup instanceof EpollEventLoopGroup){
		boot.channel(EpollSocketChannel.class);
	}else{
		boot.channel(NioSocketChannel.class);
	}
	ChannelFuture future = boot.connect(cfg.host, cfg.port);
	return future;
}
 
Example #9
Source File: NettyIoAcceptor.java    From aesh-readline with Apache License 2.0 6 votes vote down vote up
@Override
public void bind(SocketAddress address) throws IOException {
    InetSocketAddress inetAddress = (InetSocketAddress) address;
    ChannelFuture f = bootstrap.bind(inetAddress);
    Channel channel = f.channel();
    channelGroup.add(channel);
    try {
        f.sync();
        SocketAddress bound = channel.localAddress();
        boundAddresses.put(bound, channel);
        channel.closeFuture().addListener(fut -> {
            boundAddresses.remove(bound);
        });
    } catch (Exception e) {
        throw Helper.toIOException(e);
    }
}
 
Example #10
Source File: JZlibEncoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture close(final ChannelPromise promise) {
    ChannelHandlerContext ctx = ctx();
    EventExecutor executor = ctx.executor();
    if (executor.inEventLoop()) {
        return finishEncode(ctx, promise);
    } else {
        final ChannelPromise p = ctx.newPromise();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                ChannelFuture f = finishEncode(ctx(), p);
                f.addListener(new ChannelPromiseNotifier(promise));
            }
        });
        return p;
    }
}
 
Example #11
Source File: WebSocketServerHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void sendHttpResponse(
        ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example #12
Source File: StreamBufferingEncoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void receivingGoAwayFailsBufferedStreams() {
    encoder.writeSettingsAck(ctx, newPromise());
    setMaxConcurrentStreams(5);

    int streamId = 3;
    List<ChannelFuture> futures = new ArrayList<ChannelFuture>();
    for (int i = 0; i < 9; i++) {
        futures.add(encoderWriteHeaders(streamId, newPromise()));
        streamId += 2;
    }
    assertEquals(4, encoder.numBufferedStreams());

    connection.goAwayReceived(11, 8, EMPTY_BUFFER);

    assertEquals(5, connection.numActiveStreams());
    int failCount = 0;
    for (ChannelFuture f : futures) {
        if (f.cause() != null) {
            failCount++;
        }
    }
    assertEquals(9, failCount);
    assertEquals(0, encoder.numBufferedStreams());
}
 
Example #13
Source File: NettyResponseChannel.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
  Throwable cause = future.cause() == null ? exception : future.cause();
  if (cause != null) {
    handleChannelWriteFailure(cause, false);
  } else {
    cleanupChunks(null);
  }
  logger.debug("Chunk cleanup complete on channel {}", ctx.channel());
}
 
Example #14
Source File: Server.java    From netty-custom-protocol with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	//ONE:
	//1 用于接受客户端连接的线程工作组
	EventLoopGroup boss = new NioEventLoopGroup();
	//2 用于对接受客户端连接读写操作的线程工作组
	EventLoopGroup work = new NioEventLoopGroup();
	
	//TWO:
	//3 辅助类。用于帮助我们创建NETTY服务
	ServerBootstrap b = new ServerBootstrap();
	b.group(boss, work)	//绑定两个工作线程组
	 .channel(NioServerSocketChannel.class)	//设置NIO的模式
	 .option(ChannelOption.SO_BACKLOG, 1024)	//设置TCP缓冲区
	 //.option(ChannelOption.SO_SNDBUF, 32*1024)	// 设置发送数据的缓存大小
	 .option(ChannelOption.SO_RCVBUF, 32*1024)	// 设置接受数据的缓存大小
	 .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)	// 设置保持连接
	 .childOption(ChannelOption.SO_SNDBUF, 32*1024)
	 // 初始化绑定服务通道
	 .childHandler(new ChannelInitializer<SocketChannel>() {
		@Override
		protected void initChannel(SocketChannel sc) throws Exception {
			sc.pipeline().addLast(new NettyMessageDecoder(1024*1024*5, 4, 4));
			sc.pipeline().addLast(new NettyMessageEncoder());
			sc.pipeline().addLast("readTimeoutHandler",new ReadTimeoutHandler(50));
			sc.pipeline().addLast("LoginAuthHandler",new LoginAuthRespHandler());
			sc.pipeline().addLast("HeartBeatHandler",new HeartBeatRespHandler());
			sc.pipeline().addLast(new ServerHandler());
		}
	 });
	
	ChannelFuture cf = b.bind(NettyConstant.REMOTEIP,NettyConstant.PORT).sync();
	
	System.out.println("Netty server start ok : "
			+ (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
	
	//释放连接
	cf.channel().closeFuture().sync();
	work.shutdownGracefully();
	boss.shutdownGracefully();
}
 
Example #15
Source File: HttpHandler.java    From qonduit with Apache License 2.0 5 votes vote down vote up
default void sendResponse(ChannelHandlerContext ctx, Object msg) {
    ChannelFuture f = ctx.writeAndFlush(msg);
    LOG.trace(Constants.LOG_RETURNING_RESPONSE, msg);
    if (!f.isSuccess()) {
        LOG.error(Constants.ERR_WRITING_RESPONSE, f.cause());
    }
}
 
Example #16
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example #17
Source File: WriteBufferingAndExceptionHandlerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void uncaughtReadFails() throws Exception {
  WriteBufferingAndExceptionHandler handler =
      new WriteBufferingAndExceptionHandler(new ChannelHandlerAdapter() {});
  LocalAddress addr = new LocalAddress("local");
  ChannelFuture cf = new Bootstrap()
      .channel(LocalChannel.class)
      .handler(handler)
      .group(group)
      .register();
  chan = cf.channel();
  cf.sync();
  ChannelFuture sf = new ServerBootstrap()
      .channel(LocalServerChannel.class)
      .childHandler(new ChannelHandlerAdapter() {})
      .group(group)
      .bind(addr);
  server = sf.channel();
  sf.sync();

  ChannelFuture wf = chan.writeAndFlush(new Object());
  chan.connect(addr);
  chan.pipeline().fireChannelRead(Unpooled.copiedBuffer(new byte[] {'a'}));

  try {
    wf.sync();
    fail();
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
    assertThat(status.getDescription()).contains("channelRead() missed");
  }
}
 
Example #18
Source File: DoradoServer.java    From dorado with Apache License 2.0 5 votes vote down vote up
public void start() {
	// print dorado ascii-art logo,use figlet generate ascii-art logo
	if (!Dorado.springInitialized) {
		System.out.println(ClassLoaderUtils.getResoureAsString("dorado-ascii"));
		System.out.println();
	}

	if (builder.isSpringOn() && !Dorado.springInitialized) {
		SpringContainer.create(builder.scanPackages());
	}

	Webapp.create(builder.scanPackages(), builder.isSpringOn());

	EventLoopGroup acceptor = new NioEventLoopGroup(builder.getAcceptors());
	EventLoopGroup worker = new NioEventLoopGroup(builder.getIoWorkers());

	ServerBootstrap bootstrap = null;
	try {
		bootstrap = new ServerBootstrap().group(acceptor, worker).channel(NioServerSocketChannel.class)
				.childHandler(new DoradoChannelInitializer(builder));

		bootstrap.option(ChannelOption.SO_BACKLOG, builder.getBacklog());
		bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
		bootstrap.childOption(ChannelOption.SO_SNDBUF, builder.getSendBuffer());
		bootstrap.childOption(ChannelOption.SO_RCVBUF, builder.getRecvBuffer());

		ChannelFuture f = bootstrap.bind(builder.getPort()).sync();
		LogUtils.info(String.format("Dorado application initialized with port: %d (http)", builder.getPort()));
		f.channel().closeFuture().sync();     
	} catch (Throwable ex) {
		LogUtils.error("Start dorado application failed, cause: " + ex.getMessage(), ex);
	} finally {
		worker.shutdownGracefully();
		acceptor.shutdownGracefully();
	}
}
 
Example #19
Source File: RemotingNettyServer.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() {
    try {
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
        bootstrap.localAddress(serverconfig.getListenPort());
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws IOException {

                ch.pipeline().addLast("idleState", new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
                ch.pipeline().addLast("heartbeat", new HeartbeatHandler());
                ch.pipeline().addLast(new KyroMsgDecoder());
                ch.pipeline().addLast(new KyroMsgEncoder());
                ch.pipeline().addLast("invoker", new NettyServerHandler());
            }
        });

        ChannelFuture channelFuture = this.bootstrap.bind().sync();
        //        channelFuture.channel().closeFuture().sync();
        logger.info("server started on port:" + serverconfig.getListenPort());
        respScheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                scanResponseTable(5000);
            }
        }, 60 * 1000, 60 * 1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        logger.error("", e);
        System.exit(-1);
    }
}
 
Example #20
Source File: EchoServerHandlerWithFuture.java    From netty.book.kor with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ChannelFuture channelFuture = ctx.writeAndFlush(msg);

    final int writeMessageSize = ((ByteBuf) msg).readableBytes();

    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            System.out.println("전송한 Byte : " + writeMessageSize);
            future.channel().close();
        }
    });
}
 
Example #21
Source File: NettyServer.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
* Netty创建全部都是实现自AbstractBootstrap。
* 客户端的是Bootstrap,服务端的则是	ServerBootstrap。
**/
  public static void main(String[] args) throws InterruptedException {
      try {
          b.group(group);
          b.channel(NioServerSocketChannel.class);
          b.childHandler(new NettyServerFilter()); //设置过滤器
          // 异步地绑定服务器;调用 sync()方法阻塞  等待直到绑定完成
          ChannelFuture f = b.bind(port).sync();
          System.out.println("服务端启动成功,端口是:"+port);
          // 获取 Channel 的  CloseFuture,并且阻塞当前线程直到它完成
          f.channel().closeFuture().sync();
      } finally {
          group.shutdownGracefully(); //关闭EventLoopGroup,释放掉所有资源包括创建的线程  
      }
  }
 
Example #22
Source File: OioDatagramChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress, ChannelPromise promise) {
    ensureBound();
    try {
        socket.joinGroup(multicastAddress);
        promise.setSuccess();
    } catch (IOException e) {
        promise.setFailure(e);
    }
    return promise;
}
 
Example #23
Source File: HttpXmlClient.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void connect(int port) throws Exception {
    // 配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch)
                            throws Exception {
                        ch.pipeline().addLast("http-decoder",
                                new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator",
                                new HttpObjectAggregator(65536));
                        // XML解码器
                        ch.pipeline().addLast(
                                "xml-decoder",
                                new HttpXmlResponseDecoder(Order.class,
                                        true));
                        ch.pipeline().addLast("http-encoder",
                                new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder",
                                new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler",
                                new HttpXmlClientHandler());
                    }
                });

        // 发起异步连接操作
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 当代客户端链路关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
 
Example #24
Source File: DefaultRedisSlave.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture onCommand(ReferenceFileRegion referenceFileRegion) {

	closeState.makeSureOpen();
	logger.debug("[onCommand]{}, {}", this, referenceFileRegion);
	return doWriteFile(referenceFileRegion);
}
 
Example #25
Source File: ActionDispatcher.java    From nettice with Apache License 2.0 5 votes vote down vote up
private void writeResponse(boolean forceClose){
	boolean close = isClose();
	if(!close && !forceClose){
		response.headers().add(HttpHeaders.CONTENT_LENGTH, String.valueOf(response.content().readableBytes()));
	}
	ChannelFuture future = channel.write(response);
	if(close || forceClose){
		future.addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example #26
Source File: NettyClientHandlerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void receivedGoAwayShouldRefuseLaterStreamId() throws Exception {
  ChannelFuture future = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));
  channelRead(goAwayFrame(streamId - 1));
  verify(streamListener).closed(any(Status.class), eq(REFUSED), any(Metadata.class));
  assertTrue(future.isDone());
}
 
Example #27
Source File: ByteTransfer.java    From incubator-nemo with Apache License 2.0 5 votes vote down vote up
/**
 * @param remoteExecutorId id of the remote executor
 * @return {@link ContextManager} for the channel to the specified executor
 */
private CompletableFuture<ContextManager> connectTo(final String remoteExecutorId) {
  final CompletableFuture<ContextManager> completableFuture = new CompletableFuture<>();
  final ChannelFuture channelFuture;
  try {
    channelFuture = executorIdToChannelFutureMap.compute(remoteExecutorId, (executorId, cachedChannelFuture) -> {
      if (cachedChannelFuture != null
        && (cachedChannelFuture.channel().isOpen() || cachedChannelFuture.channel().isActive())) {
        return cachedChannelFuture;
      } else {
        final ChannelFuture future = byteTransport.connectTo(executorId);
        future.channel().closeFuture().addListener(f -> executorIdToChannelFutureMap.remove(executorId, future));
        return future;
      }
    });
  } catch (final RuntimeException e) {
    completableFuture.completeExceptionally(e);
    return completableFuture;
  }
  channelFuture.addListener(future -> {
    if (future.isSuccess()) {
      completableFuture.complete(channelFuture.channel().pipeline().get(ContextManager.class));
    } else {
      executorIdToChannelFutureMap.remove(remoteExecutorId, channelFuture);
      completableFuture.completeExceptionally(future.cause());
    }
  });
  return completableFuture;
}
 
Example #28
Source File: NettyBasicTcpTransport.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<Channel> getChannel(M address) {
    final CompletableFuture<Channel> channelFuture = new CompletableFuture<>();
    ChannelFuture f = getBootstrap().connect(address.recipient());
    //Acquire from pool and listen for completion
    f.addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            channelFuture.complete(future.channel());
        } else {
            channelFuture.completeExceptionally(future.cause());
        }
    });
    return channelFuture;
}
 
Example #29
Source File: NettyClientHandlerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void receivedGoAwayShouldFailUnknownBufferedStreams() throws Exception {
  receiveMaxConcurrentStreams(0);

  ChannelFuture future = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));

  // Read a GOAWAY that indicates our stream was never processed by the server.
  channelRead(goAwayFrame(0, 8 /* Cancel */, Unpooled.copiedBuffer("this is a test", UTF_8)));
  assertTrue(future.isDone());
  assertFalse(future.isSuccess());
  Status status = Status.fromThrowable(future.cause());
  assertEquals(Status.CANCELLED.getCode(), status.getCode());
  assertEquals("HTTP/2 error code: CANCEL\nReceived Goaway\nthis is a test",
      status.getDescription());
}
 
Example #30
Source File: NioDatagramChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture joinGroup(InetAddress multicastAddress, ChannelPromise promise) {
    try {
        return joinGroup(
                multicastAddress,
                NetworkInterface.getByInetAddress(localAddress().getAddress()),
                null, promise);
    } catch (SocketException e) {
        promise.setFailure(e);
    }
    return promise;
}