congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
ClientBootstrap
Code IndexAdd Tabnine to your IDE (free)

How to use
ClientBootstrap
in
org.jboss.netty.bootstrap

Best Java code snippets using org.jboss.netty.bootstrap.ClientBootstrap (Showing top 20 results out of 909)

Refine searchRefine arrow

  • ChannelFuture
  • Channel
  • InetSocketAddress
  • NioClientSocketChannelFactory
  • Executors
origin: MovingBlocks/Terasology

  hibernationSettings.get().setHibernationAllowed(false);
factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
ClientBootstrap bootstrap = new ClientBootstrap(factory);
bootstrap.setPipelineFactory(new TerasologyClientPipelineFactory(this));
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);
ChannelFuture connectCheck = bootstrap.connect(new InetSocketAddress(address, port));
try {
  connectCheck.await();
} catch (InterruptedException e) {
  connectCheck.cancel();
  connectCheck.getChannel().getCloseFuture().awaitUninterruptibly();
  factory.releaseExternalResources();
  throw e;
if (!connectCheck.isSuccess()) {
  logger.warn("Failed to connect to server", connectCheck.getCause());
  connectCheck.getChannel().getCloseFuture().awaitUninterruptibly();
  factory.releaseExternalResources();
  return new JoinStatusImpl("Failed to connect to server - " + connectCheck.getCause().getMessage());
} else {
  allChannels.add(connectCheck.getChannel());
  ClientConnectionHandler connectionHandler = connectCheck.getChannel().getPipeline().get(ClientConnectionHandler.class);
  if (connectionHandler == null) {
    JoinStatusImpl status = new JoinStatusImpl();
origin: apache/incubator-druid

 @Override
 public void stop()
 {
  bootstrap.releaseExternalResources();
 }
}
origin: alibaba/jstorm

public void start() {
  bootstrap = new ClientBootstrap(clientChannelFactory);
  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("reuseAddress", true);
  bootstrap.setOption("sendBufferSize", bufferSize);
  bootstrap.setOption("keepAlive", true);
  // Set up the pipeline factory.
  bootstrap.setPipelineFactory(new StormClientPipelineFactory(this, stormConf));
  reconnect();
}
origin: MovingBlocks/Terasology

public ServerInfoService() {
  pool = Executors.newCachedThreadPool();
  factory = new NioClientSocketChannelFactory(pool, pool, 1, 1);
  bootstrap = new ClientBootstrap(factory);
  bootstrap.setPipelineFactory(new InfoRequestPipelineFactory());
  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);
}
origin: io.netty/netty

/**
 * Attempts a new connection with the specified {@code remoteAddress} and
 * the current {@code "localAddress"} option. If the {@code "localAddress"}
 * option is not set, the local address of a new channel is determined
 * automatically.  This method is identical with the following code:
 *
 * <pre>
 * {@link ClientBootstrap} b = ...;
 * b.connect(remoteAddress, b.getOption("localAddress"));
 * </pre>
 *
 * @return a future object which notifies when this connection attempt
 *         succeeds or fails
 *
 * @throws ClassCastException
 *         if {@code "localAddress"} option's value is
 *            neither a {@link SocketAddress} nor {@code null}
 * @throws ChannelPipelineException
 *         if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory}
 *            failed to create a new {@link ChannelPipeline}
 */
public ChannelFuture connect(SocketAddress remoteAddress) {
  if (remoteAddress == null) {
    throw new NullPointerException("remoteAddress");
  }
  SocketAddress localAddress = (SocketAddress) getOption("localAddress");
  return connect(remoteAddress, localAddress);
}
origin: wg/lettuce

/**
 * Create a new client that connects to the supplied host and port. Connection
 * attempts and non-blocking commands will {@link #setDefaultTimeout timeout}
 * after 60 seconds.
 *
 * @param host    Server hostname.
 * @param port    Server port.
 */
public RedisClient(String host, int port) {
  ExecutorService connectors = Executors.newFixedThreadPool(1);
  ExecutorService workers    = Executors.newCachedThreadPool();
  ClientSocketChannelFactory factory = new NioClientSocketChannelFactory(connectors, workers);
  InetSocketAddress addr = new InetSocketAddress(host, port);
  bootstrap = new ClientBootstrap(factory);
  bootstrap.setOption("remoteAddress", addr);
  setDefaultTimeout(60, TimeUnit.SECONDS);
  channels = new DefaultChannelGroup();
  timer    = new HashedWheelTimer();
}
origin: ml.shifu/guagua-yarn

/**
 * Connect to app master for status RPC report.
 */
private void initRPCClient() {
  this.rpcClient = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newSingleThreadExecutor(),
      Executors.newSingleThreadExecutor()));
  // Set up the pipeline factory.
  this.rpcClient.setPipelineFactory(new ChannelPipelineFactory() {
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new ObjectEncoder(),
          new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())),
          new ClientHandler());
    }
  });
  // Start the connection attempt.
  ChannelFuture future = this.rpcClient.connect(new InetSocketAddress(this.rpcHostName, this.rpcPort));
  LOG.info("Connect to {}:{}", this.rpcHostName, this.rpcPort);
  this.rpcClientChannel = future.awaitUninterruptibly().getChannel();
}
origin: com.github.jiayuhan-it/hadoop-nfs

 public void run() {
  // Configure the client.
  ChannelFactory factory = new NioClientSocketChannelFactory(
    Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 1, 1);
  ClientBootstrap bootstrap = new ClientBootstrap(factory);

  // Set up the pipeline factory.
  bootstrap.setPipelineFactory(setPipelineFactory());

  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);

  // Start the connection attempt.
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

  if (oneShot) {
   // Wait until the connection is closed or the connection attempt fails.
   future.getChannel().getCloseFuture().awaitUninterruptibly();

   // Shut down thread pools to exit.
   bootstrap.releaseExternalResources();
  }
 }
}
origin: kakaochatfriend/KakaoChatFriendAPI

@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
  try{ Thread.sleep(1000); } catch(Exception ex) { }
  bootstrap.connect(new InetSocketAddress(host, port));
}
origin: net.sourceforge.openutils/flazr

public static void connect(final ClientOptions options) {  
  final ClientBootstrap bootstrap = getBootstrap(Executors.newCachedThreadPool(), options);
  final ChannelFuture future = bootstrap.connect(new InetSocketAddress(options.getHost(), options.getPort()));
  future.awaitUninterruptibly();
  if(!future.isSuccess()) {
    // future.getCause().printStackTrace();
    logger.error("error creating client connection: {}", future.getCause().getMessage());
  }
  future.getChannel().getCloseFuture().awaitUninterruptibly(); 
  bootstrap.getFactory().releaseExternalResources();
}
origin: com.ning/async-http-client

private ChannelFuture connect(Request request, Uri uri, ProxyServer proxy, boolean useProxy, ClientBootstrap bootstrap, AsyncHandler<?> asyncHandler) throws UnknownHostException {
  InetSocketAddress remoteAddress = remoteAddress(request, uri, proxy, useProxy);
  if (asyncHandler instanceof AsyncHandlerExtensions)
    AsyncHandlerExtensions.class.cast(asyncHandler).onDnsResolved(remoteAddress.getAddress());
  if (request.getLocalAddress() != null)
    return bootstrap.connect(remoteAddress, new InetSocketAddress(request.getLocalAddress(), 0));
  else
    return bootstrap.connect(remoteAddress);
}
origin: AlbinTheander/MeQanTT

public void connect(String host, int port) {
  bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
      Executors.newCachedThreadPool(),
      Executors.newCachedThreadPool()));
  handler = new MqttMessageHandler();
  handler.setListener(listener);
  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new MqttMessageEncoder(),
          new MqttMessageDecoder(), handler);
    }
  });
  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
      port));
  channel = future.awaitUninterruptibly().getChannel();
  if (!future.isSuccess()) {
    future.getCause().printStackTrace();
    bootstrap.releaseExternalResources();
    return;
  }
  channel.write(new ConnectMessage(id, true, 30));
  // TODO: Should probably wait for the ConnAck message
}
origin: kangfoo/nettyDefinitiveGuide

public void connect() {
  clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
  clientBootstrap.setOption("tcpNoDelay", true);
  clientBootstrap.setPipelineFactory(new ClientPipelineFactory());
  while (true) {
    ChannelFuture future = clientBootstrap.connect(new InetSocketAddress(ip, Integer.parseInt(port)));
    future.awaitUninterruptibly(5000);
    if (future.isDone()) {
      channel = future.getChannel();
      if (channel != null && channel.isConnected()) {
        break;
      }
    }
  }
}
origin: hadooparchitecturebook/hadoop-arch-book

public void startClient() {
 ClientBootstrap bootstrap = new ClientBootstrap(
     new NioClientSocketChannelFactory(
         Executors.newCachedThreadPool(),
         Executors.newCachedThreadPool()));
 try {
  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
   public ChannelPipeline getPipeline() {
    ChannelPipeline p = Channels.pipeline();
    handler = new NettyClientHandler();
    p.addLast("handler", handler);
    return p;
   }
  });
  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("receiveBufferSize", 1048576);
  bootstrap.setOption("sendBufferSize", 1048576);
  // Start the connection attempt.
  LOG.info("EventClient: Connecting " + host + "," + port);
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
  LOG.info("EventClient: Connected " + host + "," + port);
  allChannels = new DefaultChannelGroup();
  // Wait until the connection is closed or the connection attempt fails.
  allChannels.add(future.getChannel());
  LOG.info("EventClient: Added to Channels ");
 } catch (Exception e) {
  e.printStackTrace();
 }
}
origin: net.sourceforge.openutils/flazr

@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {        
  final Channel inboundChannel = e.getChannel();
  RtmpProxy.ALL_CHANNELS.add(inboundChannel);
  inboundChannel.setReadable(false);        
  ClientBootstrap cb = new ClientBootstrap(cf);
  cb.getPipeline().addLast("handshaker", new ProxyHandshakeHandler());
  cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
  ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));
  outboundChannel = f.getChannel();
  f.addListener(new ChannelFutureListener() {
    @Override public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        logger.info("connected to remote host: {}, port: {}", remoteHost, remotePort);
        inboundChannel.setReadable(true);
      } else {                    
        inboundChannel.close();
      }
    }
  });
}
origin: lihengming/java-codes

public static void main(String args[]) {
  // Client服务启动器
  ClientBootstrap bootstrap = new ClientBootstrap(
      new NioClientSocketChannelFactory(
          Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));
  // 设置一个处理服务端消息和各种消息事件的类(Handler)
  bootstrap.setPipelineFactory(() -> Channels.pipeline(new HelloClientHandler()));
  // 连接到本地的8000端口的服务端
  bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
}
origin: MovingBlocks/Terasology

public Future<ServerInfoMessage> requestInfo(final String address, final int port) {
  return pool.submit(() -> {
    InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
    ChannelFuture connectCheck = bootstrap.connect(remoteAddress);
    connectCheck.syncUninterruptibly();
    Channel channel = connectCheck.getChannel();
    channel.getCloseFuture().syncUninterruptibly();
    ServerInfoRequestHandler handler = channel.getPipeline().get(ServerInfoRequestHandler.class);
    ServerInfoMessage serverInfo = handler.getServerInfo();
    return serverInfo;
  });
}
origin: stackoverflow.com

 // Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
    new NioClientSocketChannelFactory(
        Executors.newCachedThreadPool(),
        Executors.newCachedThreadPool()));


ChannelFuture future = null;

while (true)
{
  future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 80));
  future.awaitUninterruptibly();
  if (future.isSuccess()) 
  {
    break;
  }
}
origin: weibocom/motan

channelFuture = nettyClient.getBootstrap().connect(
    new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort()));
boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
boolean success = channelFuture.isSuccess();
  channel = channelFuture.getChannel();
  if (channel.getLocalAddress() != null && channel.getLocalAddress() instanceof InetSocketAddress) {
    localAddress = (InetSocketAddress) channel.getLocalAddress();
origin: apache/incubator-druid

final int port = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
final ChannelFuture retVal;
final ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(host, port));
 final ChannelPipeline pipeline = connectFuture.getChannel().getPipeline();
 pipeline.addFirst("ssl", sslHandler);
 final ChannelFuture handshakeFuture = Channels.future(connectFuture.getChannel());
 pipeline.addLast("connectionErrorHandler", new SimpleChannelUpstreamHandler()
 connectFuture.addListener(
   new ChannelFutureListener()
org.jboss.netty.bootstrapClientBootstrap

Javadoc

A helper class which creates a new client-side Channel and makes a connection attempt.

Configuring a channel

#setOption(String,Object) are used to configure a channel:
 
ClientBootstrap b = ...; 
// Options for a new channel 
b.setOption("remoteAddress", new  
InetSocketAddress("example.com", 8080)); 
b.setOption("tcpNoDelay", true); 
b.setOption("receiveBufferSize", 1048576); 
For the detailed list of available options, please refer to ChannelConfig and its sub-types.

Configuring a channel pipeline

Every channel has its own ChannelPipeline and you can configure it in two ways. The recommended approach is to specify a ChannelPipelineFactory by calling #setPipelineFactory(ChannelPipelineFactory).
 
ClientBootstrap b = ...; 
b.setPipelineFactory(new MyPipelineFactory()); 
public class MyPipelineFactory implements  
ChannelPipelineFactory { 
public  
ChannelPipeline getPipeline() throws Exception { 
// Create and configure a new pipeline for a new channel. 
ChannelPipeline p =  
Channels.pipeline(); 
p.addLast("encoder", new EncodingHandler()); 
p.addLast("decoder", new DecodingHandler()); 
p.addLast("logic",   new LogicHandler()); 
return p; 
} 
} 

The alternative approach, which works only in a certain situation, is to use the default pipeline and let the bootstrap to shallow-copy the default pipeline for each new channel:

 
ClientBootstrap b = ...; 
ChannelPipeline p = b.getPipeline(); 
// Add handlers to the default pipeline. 
p.addLast("encoder", new EncodingHandler()); 
p.addLast("decoder", new DecodingHandler()); 
p.addLast("logic",   new LogicHandler()); 
Please note 'shallow-copy' here means that the added ChannelHandlers are not cloned but only their references are added to the new pipeline. Therefore, you cannot use this approach if you are going to open more than one Channels or run a server that accepts incoming connections to create its child channels.

Applying different settings for different Channels

ClientBootstrap is just a helper class. It neither allocates nor manages any resources. What manages the resources is the ChannelFactory implementation you specified in the constructor of ClientBootstrap. Therefore, it is OK to create as many ClientBootstrap instances as you want with the same ChannelFactory to apply different settings for different Channels.

Most used methods

  • connect
    Attempts a new connection with the specified remoteAddress and the specified localAddress. If the sp
  • <init>
    Creates a new instance with the specified initial ChannelFactory.
  • setPipelineFactory
  • setOption
  • releaseExternalResources
  • getPipeline
  • getFactory
  • setOptions
  • getOption
  • getOptions
  • shutdown
  • getPipelineFactory
  • shutdown,
  • getPipelineFactory,
  • setPipeline,
  • setFactory

Popular in Java

  • Reactive rest calls using spring rest template
  • getSupportFragmentManager (FragmentActivity)
  • getExternalFilesDir (Context)
  • scheduleAtFixedRate (Timer)
  • Color (java.awt)
    The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
  • Date (java.util)
    A specific moment in time, with millisecond precision. Values typically come from System#currentTime
  • GregorianCalendar (java.util)
    GregorianCalendar is a concrete subclass of Calendarand provides the standard calendar used by most
  • AtomicInteger (java.util.concurrent.atomic)
    An int value that may be updated atomically. See the java.util.concurrent.atomic package specificati
  • JTextField (javax.swing)
  • Base64 (org.apache.commons.codec.binary)
    Provides Base64 encoding and decoding as defined by RFC 2045.This class implements section 6.8. Base
  • Best plugins for Eclipse
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now