io.netty.bootstrap.Bootstrap.connect()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.9k)|赞(0)|评价(0)|浏览(588)

本文整理了Java中io.netty.bootstrap.Bootstrap.connect()方法的一些代码示例,展示了Bootstrap.connect()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Bootstrap.connect()方法的具体详情如下:
包路径:io.netty.bootstrap.Bootstrap
类名称:Bootstrap
方法名:connect

Bootstrap.connect介绍

[英]Connect a Channel to the remote peer.
[中]将通道连接到远程对等方。

代码示例

代码示例来源:origin: alibaba/canal

public static SocketChannel open(SocketAddress address) throws Exception {
  SocketChannel socket = null;
  ChannelFuture future = boot.connect(address).sync();
  if (future.isSuccess()) {
    future.channel().pipeline().get(BusinessHandler.class).latch.await();
    socket = chManager.get(future.channel());
  }
  if (null == socket) {
    throw new IOException("can't create socket!");
  }
  return socket;
}

代码示例来源:origin: blynkkk/blynk-server

public void start() {
  Bootstrap b = new Bootstrap();
  b.group(nioEventLoopGroup).channel(NioSocketChannel.class).handler(getChannelInitializer());
  try {
    // Start the connection attempt.
    this.channel = b.connect(host, port).sync().channel();
  } catch (InterruptedException e) {
    log.error(e);
  }
}

代码示例来源:origin: eclipse-vertx/vert.x

private void handleConnect(SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, Handler<AsyncResult<Channel>> channelHandler) {
 VertxInternal vertx = context.owner();
 bootstrap.resolver(vertx.nettyAddressResolverGroup());
 bootstrap.handler(new ChannelInitializer<Channel>() {
  @Override
  protected void initChannel(Channel ch) {
   initSSL(peerAddress, serverName, ch, channelHandler);
  }
 });
 ChannelFuture fut = bootstrap.connect(vertx.transport().convert(remoteAddress, false));
 fut.addListener(res -> {
  if (res.isSuccess()) {
   connected(fut.channel(), channelHandler);
  } else {
   channelHandler.handle(io.vertx.core.Future.failedFuture(res.cause()));
  }
 });
}

代码示例来源:origin: eclipse-vertx/vert.x

AtomicReference<Thread> channelThread = new AtomicReference<>();
CountDownLatch connectLatch = new CountDownLatch(1);
Bootstrap bootstrap = new Bootstrap();
bootstrap.channelFactory(((VertxInternal)vertx).transport().channelFactory(false));
bootstrap.group(vertx.nettyEventLoopGroup());
bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup());
bootstrap.handler(new ChannelInitializer<Channel>() {
 @Override
 protected void initChannel(Channel ch) throws Exception {
ChannelFuture channelFut = bootstrap.connect("localhost", 1234);
awaitLatch(connectLatch);
channelFut.addListener(v -> {

代码示例来源:origin: fengjiachun/Jupiter

@Override
public void run(Timeout timeout) throws Exception {
  if (!isReconnectNeeded()) {
    logger.warn("Cancel reconnecting with {}.", remoteAddress);
    return;
  }
  ChannelFuture future;
  synchronized (bootstrap) {
    bootstrap.handler(new ChannelInitializer<Channel>() {
      @Override
      protected void initChannel(Channel ch) throws Exception {
        ch.pipeline().addLast(handlers());
      }
    });
    future = bootstrap.connect(remoteAddress);
  }
  future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture f) throws Exception {
      boolean succeed = f.isSuccess();
      logger.warn("Reconnects with {}, {}.", remoteAddress, succeed ? "succeed" : "failed");
      if (!succeed) {
        f.channel().pipeline().fireChannelInactive();
      }
    }
  });
}

代码示例来源:origin: relayrides/pushy

@Override
  public void run() {
    final Bootstrap bootstrap = ApnsChannelFactory.this.bootstrapTemplate.clone()
        .channelFactory(new AugmentingReflectiveChannelFactory<>(
            ClientChannelClassUtil.getSocketChannelClass(ApnsChannelFactory.this.bootstrapTemplate.config().group()),
            CHANNEL_READY_PROMISE_ATTRIBUTE_KEY, channelReadyPromise));
    final ChannelFuture connectFuture = bootstrap.connect();
    connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {
      @Override
      public void operationComplete(final ChannelFuture future) {
        if (!future.isSuccess()) {
          // This may seem spurious, but our goal here is to accurately report the cause of
          // connection failure; if we just wait for connection closure, we won't be able to
          // tell callers anything more specific about what went wrong.
          tryFailureAndLogRejectedCause(channelReadyPromise, future.cause());
        }
      }
    });
    connectFuture.channel().closeFuture().addListener(new GenericFutureListener<ChannelFuture> () {
      @Override
      public void operationComplete(final ChannelFuture future) {
        // We always want to try to fail the "channel ready" promise if the connection closes; if it has
        // already succeeded, this will have no effect.
        channelReadyPromise.tryFailure(
            new IllegalStateException("Channel closed before HTTP/2 preface completed."));
      }
    });
  }
}, delay, TimeUnit.SECONDS);

代码示例来源:origin: hengyunabc/xdiamond

@Override
 public void run() {
  logger.info("Reconnecting to {}:{}", serverAddress, port);
  configureBootstrap(new Bootstrap(), loop).connect().addListener(new FutureListener<Void>() {
   @Override
   public void operationComplete(Future<Void> future) throws Exception {
    if (!future.isSuccess()) {
     logger.error("can not connection to {}:{}", serverAddress, port, future.cause());
    } else {
     logger.info("connection to {}:{} success.", serverAddress, port);
    }
   }
  });
 }
}, currentRetryInterval, TimeUnit.SECONDS);

代码示例来源:origin: a2888409/face2face

public static void startGateLogicConnection(String ip, int port) {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap()
        .group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel channel)
              throws Exception {
            ChannelPipeline pipeline = channel.pipeline();

            pipeline.addLast("MessageDecoder", new PacketDecoder());
            pipeline.addLast("MessageEncoder", new PacketEncoder());

            pipeline.addLast("GateLogicConnectionHandler", new GateLogicConnectionHandler());  //logic -> gate
          }
        });

    bootstrap.connect(ip, port);

  }
}

代码示例来源:origin: mpusher/mpush

public ChannelFuture connect(InetSocketAddress remote, InetSocketAddress local, ClientConfig clientConfig) {
  ChannelFuture future = local != null ? bootstrap.connect(remote, local) : bootstrap.connect(remote);
  if (future.channel() != null) future.channel().attr(CONFIG_KEY).set(clientConfig);
  future.addListener(f -> {
    if (f.isSuccess()) {
      future.channel().attr(CONFIG_KEY).set(clientConfig);
      LOGGER.info("start netty client success, remote={}, local={}", remote, local);
    } else {
      LOGGER.error("start netty client failure, remote={}, local={}", remote, local, f.cause());
    }
  });
  return future;
}

代码示例来源:origin: fengjiachun/Jupiter

ChannelFuture future;
  synchronized (bootstrapLock()) {
    boot.handler(new ChannelInitializer<Channel>() {
    future = boot.connect(socketAddress);
  channel = future.channel();
} catch (Throwable t) {
  throw new ConnectFailedException("connects to [" + address + "] fails", t);

代码示例来源:origin: linkedin/flashback

/**
 * Establishing TCP connection to server
 *
 * @param remoteAddress remote address
 * */
public ChannelFuture connectToServer(final InetSocketAddress remoteAddress) {
 if (remoteAddress == null) {
  throw new IllegalStateException("remote address is null");
 }
 Bootstrap bootstrap = new Bootstrap().group(_upstreamWorkerGroup);
 bootstrap.channelFactory(NioSocketChannel::new);
 ServerChannelHandler serverChannelHandler = new ServerChannelHandler(this);
 bootstrap.handler(new ChannelInitializer<Channel>() {
  protected void initChannel(Channel ch)
    throws Exception {
   initChannelPipeline(ch.pipeline(), serverChannelHandler, _serverConnectionIdleTimeoutMsec);
   _serverChannel = ch;
  }
 });
 LOG.debug("Server channel is ready. About to connect....");
 return bootstrap.connect(remoteAddress);
}

代码示例来源:origin: fengjiachun/Jupiter

@Override
public void run(Timeout timeout) throws Exception {
  if (!isReconnectNeeded()) {
    logger.warn("Cancel reconnecting with {}.", remoteAddress);
    return;
  }
  ChannelFuture future;
  synchronized (bootstrap) {
    bootstrap.handler(new ChannelInitializer<Channel>() {
      @Override
      protected void initChannel(Channel ch) throws Exception {
        ch.pipeline().addLast(handlers());
      }
    });
    future = bootstrap.connect(remoteAddress);
  }
  future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture f) throws Exception {
      boolean succeed = f.isSuccess();
      logger.warn("Reconnects with {}, {}.", remoteAddress, succeed ? "succeed" : "failed");
      if (!succeed) {
        f.channel().pipeline().fireChannelInactive();
      }
    }
  });
}

代码示例来源:origin: a2888409/face2face

public static void startAuthLogicConnection(String ip, int port) {
    EventLoopGroup group = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap()
        .group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel channel)
              throws Exception {
            ChannelPipeline pipeline = channel.pipeline();

            pipeline.addLast("MessageDecoder", new PacketDecoder());
            pipeline.addLast("MessageEncoder", new PacketEncoder());
            pipeline.addLast("AuthLogicConnectionHandler", new AuthLogicConnectionHandler());  //Auth -> gate
          }
        });

    bootstrap.connect(ip, port);
  }
}

代码示例来源:origin: apache/pulsar

/**
 * Attempt to establish a TCP connection to an already resolved single IP address
 */
private CompletableFuture<Channel> connectToAddress(InetAddress ipAddress, int port) {
  CompletableFuture<Channel> future = new CompletableFuture<>();
  bootstrap.connect(ipAddress, port).addListener((ChannelFuture channelFuture) -> {
    if (channelFuture.isSuccess()) {
      future.complete(channelFuture.channel());
    } else {
      future.completeExceptionally(channelFuture.cause());
    }
  });
  return future;
}

代码示例来源:origin: fengjiachun/Jupiter

ChannelFuture future;
  synchronized (bootstrapLock()) {
    boot.handler(new ChannelInitializer<Channel>() {
    future = boot.connect(socketAddress);
  channel = future.channel();
} catch (Throwable t) {
  throw new ConnectFailedException("connects to [" + address + "] fails", t);

代码示例来源:origin: io.vertx/vertx-core

AtomicReference<Thread> channelThread = new AtomicReference<>();
CountDownLatch connectLatch = new CountDownLatch(1);
Bootstrap bootstrap = new Bootstrap();
bootstrap.channelFactory(((VertxInternal)vertx).transport().channelFactory(false));
bootstrap.group(vertx.nettyEventLoopGroup());
bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup());
bootstrap.handler(new ChannelInitializer<Channel>() {
 @Override
 protected void initChannel(Channel ch) throws Exception {
ChannelFuture channelFut = bootstrap.connect("localhost", 1234);
awaitLatch(connectLatch);
channelFut.addListener(v -> {

代码示例来源:origin: eclipse-vertx/vert.x

java.net.SocketAddress targetAddress = vertx.transport().convert(remoteAddress, false);
bootstrap.handler(new ChannelInitializer<Channel>() {
 @Override
 protected void initChannel(Channel ch) throws Exception {
ChannelFuture future = bootstrap.connect(targetAddress);

代码示例来源:origin: a2888409/face2face

public static void startGateAuthConnection(String ip, int port) {
    EventLoopGroup group = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap()
        .group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel channel)
              throws Exception {
            ChannelPipeline pipeline = channel.pipeline();

            pipeline.addLast("MessageDecoder", new PacketDecoder());
            pipeline.addLast("MessageEncoder", new PacketEncoder());
            pipeline.addLast("GateAuthConnectionHandler", new GateAuthConnectionHandler());  //Auth -> gate
          }
        });

    bootstrap.connect(ip, port);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(final HttpHeaders headers) throws IOException {
  final SettableListenableFuture<ClientHttpResponse> responseFuture = new SettableListenableFuture<>();
  ChannelFutureListener connectionListener = future -> {
    if (future.isSuccess()) {
      Channel channel = future.channel();
      channel.pipeline().addLast(new RequestExecuteHandler(responseFuture));
      FullHttpRequest nettyRequest = createFullHttpRequest(headers);
      channel.writeAndFlush(nettyRequest);
    }
    else {
      responseFuture.setException(future.cause());
    }
  };
  this.bootstrap.connect(this.uri.getHost(), getPort(this.uri)).addListener(connectionListener);
  return responseFuture;
}

代码示例来源:origin: lettuce-io/lettuce-core

redisBootstrap.handler(initializer);
ChannelFuture connectFuture = redisBootstrap.connect(redisAddress);
      RedisChannelHandler<?, ?> connection = connectionBuilder.connection();
      connection.registerCloseables(closeableResources, connection);
      channelReadyFuture.complete(connectFuture.channel());
      return;

相关文章