当前位置: 首页>>代码示例>>Java>>正文


Java Bootstrap.connect方法代码示例

本文整理汇总了Java中io.netty.bootstrap.Bootstrap.connect方法的典型用法代码示例。如果您正苦于以下问题:Java Bootstrap.connect方法的具体用法?Java Bootstrap.connect怎么用?Java Bootstrap.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在io.netty.bootstrap.Bootstrap的用法示例。


在下文中一共展示了Bootstrap.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: connectAsync

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
    ethereumListener.trace("Connecting to: " + host + ":" + port);

    EthereumChannelInitializer ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, remoteId);
    ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
    b.remoteAddress(host, port);

    b.handler(ethereumChannelInitializer);

    // Start the client.
    return b.connect();
}
 
开发者ID:talentchain,项目名称:talchain,代码行数:21,代码来源:PeerClient.java

示例2: connectAsync

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
    ethereumListener.trace("Connecting to: " + host + ":" + port);

    EthereumChannelInitializer ethereumChannelInitializer = ethereumChannelInitializerFactory.newInstance(remoteId);
    ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
    b.remoteAddress(host, port);

    b.handler(ethereumChannelInitializer);

    // Start the client.
    return b.connect();
}
 
开发者ID:rsksmart,项目名称:rskj,代码行数:21,代码来源:PeerClient.java

示例3: EchoClient

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
public EchoClient(String host, int port) {
    EventLoopGroup worker = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();

    b.group(worker)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    socketChannel.pipeline()
                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(ech);
                }
            });

    b.connect(host, port);
}
 
开发者ID:AlphaHelixDev,项目名称:AlphaLibary,代码行数:21,代码来源:EchoClient.java

示例4: channelActive

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop())
            .channel(ctx.channel().getClass())
            .handler(new CardeaServerBackendHandler(inboundChannel))
            .option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(host, port);

    outboundChannel = f.channel();

    f.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            // connection complete start to read first data
            inboundChannel.read();
        } else {
            // Close the connection if the connection attempt has failed.
            inboundChannel.close();
        }
    });
}
 
开发者ID:D3adspaceEnterprises,项目名称:cardea,代码行数:25,代码来源:CardeaServerFrontEndHandler.java

示例5: connect

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public void connect() {
  checkState(channel == null, "channel already initialized");
  try {
    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init((KeyStore) null);
    final SslContext sslContext = SslContextBuilder.forClient()
        .trustManager(trustFactory).build();
    Bootstrap bootstrap = new Bootstrap();
    final int port = uri.getPort() != -1 ? uri.getPort() : DEFAULT_WSS_PORT;
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
            p.addLast(
                new HttpClientCodec(),
                // Set the max size for the HTTP responses. This only applies to the WebSocket
                // handshake response from the server.
                new HttpObjectAggregator(32 * 1024),
                channelHandler);
          }
        });

    ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), port);
    this.channel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
              eventHandler.onError(future.cause());
            }
          }
        }
    );
  } catch (Exception e) {
    eventHandler.onError(e);
  }
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:44,代码来源:NettyWebSocketClient.java

示例6: connect

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public Connection connect(Address address, Consumer<TransportChannel> successEvent) {
	Bootstrap bootstrap = bootstrap();
	final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort());	
	
	bootstrap.handler(new ChannelInitializer<Channel>() {

		@Override
		protected void initChannel(Channel ch) throws Exception {
			ch.pipeline()
			.addLast(new Encoder(serializer))
			.addLast(new Decoder(serializer))
			.addLast(new ConsumerHandler());
		}
		
	});
	
	ChannelFuture connectChannelFuture = bootstrap.connect(socketAddress);
	connectChannelFuture.addListener(new ChannelFutureListener() {
           
           @Override
           public void operationComplete(ChannelFuture future) throws Exception {
               if (future.isSuccess()) {
               		TransportChannel transportChannel = NettyChannel.getInstance(future.channel());
               		successEvent.accept(transportChannel);
               }
           }
       });
	return new NettyConnection(connectChannelFuture);
}
 
开发者ID:DanceFirstThinkLater,项目名称:PetiteRPC,代码行数:31,代码来源:NettyConnector.java

示例7: channelRead0

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest msg) throws Exception {
    final Channel inboundChannel = ctx.channel();

    String host = msg.headers().get("Host");
    int port = 80;

    String pattern = "(http://|https://)?([^:]+)(:[\\d]+)?";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(host);
    if (m.find()) {
        host = m.group(2);
        port = (m.group(3) == null) ? 80 : Integer.parseInt(m.group(3).substring(1));
    }

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop())     // use inboundChannel thread
            .channel(ctx.channel().getClass())
            .handler(new BackendHandlerInitializer(inboundChannel));

    ChannelFuture f = b.connect(host, port);
    outboundChannel = f.channel();
    msg.retain();
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                outboundChannel.writeAndFlush(msg);
            } else {
                inboundChannel.close();
            }
        }
    });
}
 
开发者ID:biezhi,项目名称:probe,代码行数:34,代码来源:HttpFrontendHandler.java

示例8: connect

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
ChannelFuture connect(ChannelHandler... handlers) {
    SslContext sslCtx;
    try {
        sslCtx = SslContextBuilder
                .forClient()
                .trustManager(getClass().getResourceAsStream("cloudwall/exchange/gdax/gdax.pem"))
                .build();
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                    p.addLast(new HttpClientCodec());
                    p.addLast(new HttpContentDecompressor());
                    p.addLast(new HttpObjectAggregator(10485760));
                    p.addLast(handlers);
                }
            });
    return bootstrap.connect(host, port);
}
 
开发者ID:cloudwall,项目名称:libcwfincore,代码行数:28,代码来源:GdaxExchangeConnection.java

示例9: start

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public boolean start() {
    boolean result = false;
    do {
        TcpRouteDefinition route = definition.getRoute();

        if(null == route) {
            break;
        }
        if(route.getAddress() == null || route.getAddress().isEmpty()) {
            break;
        }
        if(route.getPort() == -1) {
            break;
        }

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(inbound.getClass());
            bootstrap.group(inbound.eventLoop());
            bootstrap.handler(new TcpProxyClientChannelInitializer(definition, this));
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.option(ChannelOption.AUTO_READ, false);

            ChannelFuture future = bootstrap.connect(route.getAddress(), route.getPort());
            //forwarder = future.sync().channel();
            outbound = future.channel();
            future.addListener(listener);
        } catch (Exception e) {
            log.error("Failed starting tcp proxy client.", e);
            outbound = null;
            break;
        }
        result = true;
    } while (false);
    return result;
}
 
开发者ID:thebagchi,项目名称:heimdall-proxy,代码行数:38,代码来源:TcpProxyClient.java

示例10: start

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public boolean start() {
    boolean result = false;
    do {
        List<HttpRouteDefinition> routes = definition.getRoutes();

        for(HttpRouteDefinition route: routes) {
            if (null == route) {
                break;
            }
            if (route.getInputUrl() == null || route.getInputUrl().isEmpty()) {
                break;
            }
            if (route.getScheme().equals(null)) {
                break;
            }

            try {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.channel(inbound.getClass());
                bootstrap.group(inbound.eventLoop());
                bootstrap.handler(new HttpProxyClientChannelInitializer(definition, this));
                bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
                bootstrap.option(ChannelOption.AUTO_READ, false);

                ChannelFuture future = bootstrap.connect(route.getHost(), route.getPort());
                //forwarder = future.sync().channel();
                outbound = future.channel();
                future.addListener(listener);
            } catch (Exception e) {
                log.error("Failed starting http proxy client.", e);
                outbound = null;
                break;
            }
        }
        result = true;
    } while (false);
    return result;
}
 
开发者ID:thebagchi,项目名称:heimdall-proxy,代码行数:40,代码来源:HttpProxyClient.java

示例11: main

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
public static void main(String[] args) throws InterruptedException, NoSuchAlgorithmException {
  InetSocketAddress addr = new InetSocketAddress(GOOGLE_SERVER_HOST, GOOGLE_SERVER_PORT);

  System.out.printf("Sending request to %s\n", addr);

  // Below is Netty boilerplate for setting-up an event loop and registering a handler

  NioEventLoopGroup group = new NioEventLoopGroup();
  Bootstrap bootstrap = new Bootstrap()
      .group(group)
      .remoteAddress(addr)
      .channel(NioDatagramChannel.class)
      .handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        protected void initChannel(NioDatagramChannel ch) throws Exception {
          ch.pipeline()
              .addLast(new ReadTimeoutHandler(5))
              .addLast(new RequestHandler(addr));
        }
      });

  ChannelFuture connectFuture = bootstrap.connect();
  connectFuture.addListener(fut -> {
    if (!fut.isSuccess()) {
      System.out.println("Connect fail:");
      System.out.println(fut.cause().getMessage());
    }
  });

  connectFuture.channel().closeFuture().sync();
  group.shutdownGracefully();
}
 
开发者ID:int08h,项目名称:nearenough,代码行数:33,代码来源:NettyClient.java

示例12: Bootstrap

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
 
开发者ID:naver,项目名称:hadoop,代码行数:39,代码来源:SimpleHttpProxyHandler.java

示例13: makeObject

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
public Connection makeObject(Endpoint ep) throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024);
    bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10 * 32 * 1024);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    bootstrap.group(clientGroup);
    // TODO: Make this faster:
    // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
    bootstrap.channel(clientChannelClass);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    if (enableNettyTls) {
        bootstrap.handler(new SslClientCommunicationChannelInitializer());
    } else {
        bootstrap.handler(new OnosCommunicationChannelInitializer());
    }
    // Start the client.
    CompletableFuture<Channel> retFuture = new CompletableFuture<>();
    ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port());

    f.addListener(future -> {
        if (future.isSuccess()) {
            retFuture.complete(f.channel());
        } else {
            retFuture.completeExceptionally(future.cause());
        }
    });
    log.debug("Established a new connection to {}", ep);
    return new Connection(retFuture);
}
 
开发者ID:shlee89,项目名称:athena,代码行数:33,代码来源:NettyMessagingManager.java

示例14: handleProxyData

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
private void handleProxyData(Channel channel, Object msg, boolean isHttp)
    throws Exception {
  if (cf == null) {
    if (isHttp && !(msg instanceof HttpRequest)) {  //connection异常 还有HttpContent进来,不转发
      return;
    }
    ProxyHandler proxyHandler = ProxyHandleFactory.build(proxyConfig);
    /*
      添加SSL client hello的Server Name Indication extension(SNI扩展)
      有些服务器对于client hello不带SNI扩展时会直接返回Received fatal alert: handshake_failure(握手错误)
      例如:https://cdn.mdn.mozilla.net/static/img/favicon32.7f3da72dcea1.png
     */
    RequestProto requestProto = new RequestProto(host, port, isSsl);
    ChannelInitializer channelInitializer =
        isHttp ? new HttpProxyInitializer(channel, requestProto, proxyHandler)
            : new TunnelProxyInitializer(channel, proxyHandler);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(serverConfig.getLoopGroup()) // 注册线程池
        .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
        .handler(channelInitializer);
    if (proxyConfig != null) {
      //代理服务器解析DNS和连接
      bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
    requestList = new LinkedList();
    cf = bootstrap.connect(host, port);
    cf.addListener((ChannelFutureListener) future -> {
      if (future.isSuccess()) {
        future.channel().writeAndFlush(msg);
        synchronized (requestList) {
          requestList.forEach((obj) -> future.channel().write(obj));
          requestList.clear();
          isConnect = true;
        }
      } else {
        future.channel().close();
        channel.close();
      }
    });
  } else {
    synchronized (requestList) {
      if (isConnect) {
        cf.channel().writeAndFlush(msg);
      } else {
        requestList.add(msg);
      }
    }
  }
}
 
开发者ID:monkeyWie,项目名称:proxyee,代码行数:50,代码来源:HttpProxyServerHandle.java

示例15: start

import io.netty.bootstrap.Bootstrap; //导入方法依赖的package包/类
@Override
    public synchronized void start() {
        if (isStarting) {
            return;
        }
        isStarting = true;
        nettyDistributeService.loadTxServer();

        String host = Constants.txServer.getHost();
        int port = Constants.txServer.getPort();
        final int heart = Constants.txServer.getHeart();
        int delay = Constants.txServer.getDelay();

        transactionHandler = new TransactionHandler(this, delay);
        workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    ch.pipeline().addLast("timeout", new IdleStateHandler(heart, heart, heart, TimeUnit.SECONDS));

                    ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

                    ch.pipeline().addLast(transactionHandler);
                }
            });
            // Start the client.
            logger.info("连接manager-socket服务-> host:" + host + ",port:" + port);
            ChannelFuture future = b.connect(host, port); // (5)

            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (!channelFuture.isSuccess()) {
                        channelFuture.channel().eventLoop().schedule(new Runnable() {
                            @Override
                            public void run() {
                                isStarting = false;
                                start();
                            }
                        }, 5, TimeUnit.SECONDS);
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();

//            isStarting = false;
//
//            //断开重新连接机制
//            close();
//
//            if (e instanceof ConnectTimeoutException) {
//                start();
//            }
        }
    }
 
开发者ID:1991wangliang,项目名称:tx-lcn,代码行数:65,代码来源:NettyServiceImpl.java


注:本文中的io.netty.bootstrap.Bootstrap.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。