org.jboss.netty.bootstrap.ClientBootstrap Java Examples

The following examples show how to use org.jboss.netty.bootstrap.ClientBootstrap. 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: NettyClient.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #2
Source File: RPCService.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to remote servers.  We'll initiate the connection to
 * any nodes with a lower ID so that there will be a single connection
 * between each pair of nodes which we'll use symmetrically
 */
protected void startClients(ChannelPipelineFactory pipelineFactory) {
    final ClientBootstrap bootstrap =
            new ClientBootstrap(
                 new NioClientSocketChannelFactory(bossExecutor,
                                                   workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", CONNECT_TIMEOUT);
    bootstrap.setPipelineFactory(pipelineFactory);
    clientBootstrap = bootstrap;

    ScheduledExecutorService ses = 
            syncManager.getThreadPool().getScheduledExecutor();
    reconnectTask = new SingletonTask(ses, new ConnectTask());
    reconnectTask.reschedule(0, TimeUnit.SECONDS);
}
 
Example #3
Source File: NettyClient.java    From anima with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doOpen() throws Throwable {
	bootstrap = new ClientBootstrap(channelFactory);
	bootstrap.setOption("keepAlive", true);
	bootstrap.setOption("tcpNoDelay", true);
	bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
	final NettyHandler nettyHandler = new NettyHandler(getConf(), this);
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() {
			NettyCodecAdapter adapter = new NettyCodecAdapter(getConf(),getCodec(), NettyClient.this);
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("decoder", adapter.getDecoder());
			pipeline.addLast("encoder", adapter.getEncoder());
			pipeline.addLast("handler", nettyHandler);
			return pipeline;
		}
	});
}
 
Example #4
Source File: Bootstrap.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
public void init() throws SyncException {
    cg = new DefaultChannelGroup("Cluster Bootstrap");

    bossExecutor = Executors.newCachedThreadPool();
    workerExecutor = Executors.newCachedThreadPool();

    bootstrap =
            new ClientBootstrap(new NioClientSocketChannelFactory(bossExecutor,
                                                                  workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.receiveBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", 
                        RPCService.CONNECT_TIMEOUT);
    pipelineFactory = new BootstrapPipelineFactory(this);
    bootstrap.setPipelineFactory(pipelineFactory);
}
 
Example #5
Source File: RemoteSyncManager.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@Override
public void startUp(FloodlightModuleContext context) 
        throws FloodlightModuleException {
    shutdown = false;
    bossExecutor = Executors.newCachedThreadPool();
    workerExecutor = Executors.newCachedThreadPool();
    
    final ClientBootstrap bootstrap =
            new ClientBootstrap(
                 new NioClientSocketChannelFactory(bossExecutor,
                                                   workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.receiveBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", 
                        RPCService.CONNECT_TIMEOUT);
    pipelineFactory = new RemoteSyncPipelineFactory(this);
    bootstrap.setPipelineFactory(pipelineFactory);
    clientBootstrap = bootstrap;
}
 
Example #6
Source File: NettyClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #7
Source File: NettyClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #8
Source File: NettyClient.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(() -> {
        NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("decoder", adapter.getDecoder());
        pipeline.addLast("encoder", adapter.getEncoder());
        pipeline.addLast("handler", nettyHandler);
        return pipeline;
    });
}
 
Example #9
Source File: SimpleTcpClient.java    From big-c with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example #10
Source File: NettyTCPWriter.java    From vmstats with Apache License 2.0 6 votes vote down vote up
public void connect() throws IOException {
    this.bootstrap = new ClientBootstrap(
            new NioClientSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));

    this.bootstrap.setPipelineFactory(new NettyTCPWriterPipelineFactory(this.bootstrap, this.channel, this.timer));
    //this.bootstrap.setOption("tcpNoDelay", true);
    
    // TODO: do some exception handling here
    bootstrap.setOption("remoteAddress", new InetSocketAddress(this.host, this.port));
    this.future = this.bootstrap.connect();
    this.channel = this.future.awaitUninterruptibly().getChannel();
    this.channel.setReadable(false);
    
    if(!this.future.isSuccess()){
        logger.info("NettyTCP: future unsuccessful");
    }
}
 
Example #11
Source File: Fetcher.java    From incubator-tajo with Apache License 2.0 6 votes vote down vote up
public Fetcher(URI uri, File file, ClientSocketChannelFactory factory) {
  this.uri = uri;
  this.file = file;

  String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
  this.host = uri.getHost() == null ? "localhost" : uri.getHost();
  this.port = uri.getPort();
  if (port == -1) {
    if (scheme.equalsIgnoreCase("http")) {
      this.port = 80;
    } else if (scheme.equalsIgnoreCase("https")) {
      this.port = 443;
    }
  }

  bootstrap = new ClientBootstrap(factory);
  bootstrap.setOption("connectTimeoutMillis", 5000L); // set 5 sec
  bootstrap.setOption("receiveBufferSize", 1048576); // set 1M
  bootstrap.setOption("tcpNoDelay", true);

  ChannelPipelineFactory pipelineFactory = new HttpClientPipelineFactory(file);
  bootstrap.setPipelineFactory(pipelineFactory);
}
 
Example #12
Source File: SimpleTcpClient.java    From hadoop with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example #13
Source File: NettyClientBase.java    From incubator-tajo with Apache License 2.0 6 votes vote down vote up
public void init(InetSocketAddress addr, ChannelPipelineFactory pipeFactory, ClientSocketChannelFactory factory)
    throws IOException {
  try {
    this.bootstrap = new ClientBootstrap(factory);
    this.bootstrap.setPipelineFactory(pipeFactory);
    // TODO - should be configurable
    this.bootstrap.setOption("connectTimeoutMillis", 10000);
    this.bootstrap.setOption("connectResponseTimeoutMillis", 10000);
    this.bootstrap.setOption("receiveBufferSize", 1048576 * 10);
    this.bootstrap.setOption("tcpNoDelay", true);
    this.bootstrap.setOption("keepAlive", true);

    connect(addr);
  } catch (Throwable t) {
    close();
    throw new IOException(t.getCause());
  }
}
 
Example #14
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 6 votes vote down vote up
/**
 * 文件上传
 * @param file 需要上传的文件
 * @param fileName 文件名称
 * @param thumbMark 是否需要生成缩略图
 * @return
 * @author:landyChris
 */
public static String uploadFile(File file, String fileName,
		boolean thumbMark) {
	FileClientPipelineFactory clientPipelineFactory = new FileClientPipelineFactory();
	//辅助类。用于帮助我们创建NETTY服务
	ClientBootstrap bootstrap = createClientBootstrap(clientPipelineFactory);
	String strThumbMark = Constants.THUMB_MARK_NO;
	if (thumbMark) {
		strThumbMark = Constants.THUMB_MARK_YES;
	}
	//具体处理上传文件逻辑
	uploadFile(bootstrap, FileClientContainer.getHost(),
			FileClientContainer.getPort(), file, fileName, strThumbMark,
			FileClientContainer.getUserName(),
			FileClientContainer.getPassword());
	Result result = clientPipelineFactory.getResult();
	if ((result != null) && (result.isCode())) {
		return result.getFilePath();
	}
	return null;
}
 
Example #15
Source File: NettyClient.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #16
Source File: NettyClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example #17
Source File: HttpInvoker.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
public HttpInvoker(Settings settings, ThreadPool threadPool, Headers headers, URL url) {
    super(settings, threadPool, headers);
    this.contexts = new HashMap<>();
    this.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));
    bootstrap.setPipelineFactory(new HttpInvoker.HttpClientPipelineFactory());
    bootstrap.setOption("tcpNoDelay", true);

    registerAction(BulkAction.INSTANCE, HttpBulkAction.class);
    registerAction(CreateIndexAction.INSTANCE, HttpCreateIndexAction.class);
    registerAction(RefreshAction.INSTANCE, HttpRefreshIndexAction.class);
    registerAction(ClusterUpdateSettingsAction.INSTANCE, HttpClusterUpdateSettingsAction.class);
    registerAction(UpdateSettingsAction.INSTANCE, HttpUpdateSettingsAction.class);
    registerAction(SearchAction.INSTANCE, HttpSearchAction.class);

    this.url = url;
}
 
Example #18
Source File: BgpControllerImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
private Channel connectFrom(InetSocketAddress connectToSocket, SocketAddress localAddress)
     throws InterruptedException {

     ChannelFactory channelFactory =
         new NioClientSocketChannelFactory(
                 Executors.newCachedThreadPool(),
                 Executors.newCachedThreadPool());
     ChannelPipelineFactory pipelineFactory = () -> {
         ChannelPipeline pipeline = Channels.pipeline();
         pipeline.addLast("BgpPeerFrameDecoderTest",
                 peerFrameDecoder);
         pipeline.addLast("BgpPeerChannelHandlerTest",
                 peerChannelHandler);
         return pipeline;
     };

     peerBootstrap = new ClientBootstrap(channelFactory);
     peerBootstrap.setOption("child.keepAlive", true);
     peerBootstrap.setOption("child.tcpNoDelay", true);
     peerBootstrap.setPipelineFactory(pipelineFactory);
     Channel channel = peerBootstrap.connect(connectToSocket, localAddress).getChannel();
     return channel;
}
 
Example #19
Source File: BgpControllerImplTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
  * Starts the BGP peer.
  *
  * @param connectToSocket the socket to connect to
  */
 private void connect(InetSocketAddress connectToSocket)
     throws InterruptedException {

     ChannelFactory channelFactory =
         new NioClientSocketChannelFactory(
                 Executors.newCachedThreadPool(),
                 Executors.newCachedThreadPool());
     ChannelPipelineFactory pipelineFactory = () -> {
         ChannelPipeline pipeline = Channels.pipeline();
         pipeline.addLast("BgpPeerFrameDecoderTest",
                 peerFrameDecoder);
         pipeline.addLast("BgpPeerChannelHandlerTest",
                 peerChannelHandler);
         return pipeline;
     };

     peerBootstrap = new ClientBootstrap(channelFactory);
     peerBootstrap.setOption("child.keepAlive", true);
     peerBootstrap.setOption("child.tcpNoDelay", true);
     peerBootstrap.setPipelineFactory(pipelineFactory);
     peerBootstrap.connect(connectToSocket);
}
 
Example #20
Source File: HttpElasticsearchClient.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
private HttpElasticsearchClient(Settings settings, ThreadPool threadPool, Headers headers, URL url) {
    super(settings, threadPool, headers);
    this.contextMap = Maps.newHashMap();
    this.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));
    bootstrap.setPipelineFactory(new HttpClientPipelineFactory());
    bootstrap.setOption("tcpNoDelay", true);
    this.url = url;
}
 
Example #21
Source File: NetworkFailureHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example #22
Source File: ClientControl.java    From whiteboard with Apache License 2.0 5 votes vote down vote up
/**
 * @return void
 * @description: ���ӵ������
 * @date 2015-3-16 ����10:08:27
 * @author: yems
 */
public void connect()
{
	MyThreadFactory.getInstance().getExecutorService().submit(new Runnable()
	{

		@Override
		public void run()
		{
			// Client����������
			ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
			// ����һ������������Ϣ�͸�����Ϣ�¼�����(Handler)
			bootstrap.setPipelineFactory(myChannelPipelineFactory);
			// ���ӵ�ָ��IP��ַ�ķ����
			bootstrap.setOption("key", "demokey");
			Channel channel = bootstrap.connect(new InetSocketAddress(Commons.SERVER_IP_ADDRESS, Commons.SERVER_PORT)).awaitUninterruptibly().getChannel();

			if (channel.isOpen())
			{
				Log.i(TAG, "ͨ���ɹ���");
				sendMyUUID2Server();
			} else
			{
				Log.i(TAG, "ͨ����ʧ��");
			}
		}
	});

}
 
Example #23
Source File: EventClient.java    From hadoop-arch-book with Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example #24
Source File: NettyService.java    From android-netty with Apache License 2.0 5 votes vote down vote up
/**
 * {@link Service#onCreate()}
 */
public void onCreate() {
	super.onCreate();

	ThreadManager.offer(new Runnable() {

		@Override
		public void run() {
			PowerManager.WakeLock wakeLock = WakeLockWrapper.getWakeLockInstance(NettyService.this, getWorkerTag());
			wakeLock.acquire();
			try {
				NioClientSocketChannelFactory factory = new NioClientSocketChannelFactory(
					Executors.newCachedThreadPool(), Executors.newCachedThreadPool());

				ClientBootstrap bootstrap = new ClientBootstrap(factory);

				// Set up the pipeline factory.
				bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
					public ChannelPipeline getPipeline() throws Exception {
						return Channels.pipeline(
							new ChannelDecoder(NettyService.this),
							new NetworkEventHandler(NettyService.this)
							, new ChannelEncoder(NettyService.this)
						);
					}
				});

				// Bind and start to accept incoming connections.
				ChannelFuture future = bootstrap.connect(new InetSocketAddress(SERVER_URL, SERVER_PORT));
				future.awaitUninterruptibly();
				mChannel = future.getChannel();
			} finally {
				wakeLock.release();
			}
		}
	});
}
 
Example #25
Source File: MongoProxyInboundHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable( false );

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap( cf );
    cb.setOption( "bufferFactory", HeapChannelBufferFactory.getInstance( ByteOrder.LITTLE_ENDIAN ) );
    cb.getPipeline().addLast( "framer", new MongoMessageFrame() );
    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() ) {
                // Connection attempt succeeded:
                // Begin to accept incoming traffic.
                inboundChannel.setReadable( true );
            }
            else {
                // Close the connection if the connection attempt has
                // failed.
                inboundChannel.close();
            }
        }
    } );
}
 
Example #26
Source File: NettyClientFactory.java    From migration-tool with Apache License 2.0 5 votes vote down vote up
public Client createClient(String targetIP, int targetPort, int connectTimeout) throws Exception {
	ClientBootstrap bootstrap = new ClientBootstrap(nioClient);
	bootstrap.setOption("tcpNoDelay", Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")));
	bootstrap.setOption("reuseAddress", Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
	if (connectTimeout < 1000) {
		bootstrap.setOption("connectTimeoutMillis", 1000);
	} else {
		bootstrap.setOption("connectTimeoutMillis", connectTimeout);
	}
	NettyClientHandler handler = new NettyClientHandler(this);
	bootstrap.setPipelineFactory(new NettyClientPipelineFactory(handler));
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort));
	future.awaitUninterruptibly(connectTimeout);
	if (!future.isDone()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
	}
	if (future.isCancelled()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
	}
	if (!future.isSuccess()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " error", future.getCause());
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.getCause());
	}
	NettyClient client = new NettyClient(future, connectTimeout);
	handler.setClient(client);
	return client;
}
 
Example #27
Source File: NetworkFailureHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example #28
Source File: TimestampClient.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public TimestampClient(int timeoutMillis,TimestampHostProvider timestampHostProvider) {
    this.timeoutMillis = timeoutMillis;
    this.timestampHostProvider = timestampHostProvider;
    clientCallbacks = new ConcurrentHashMap<>();
    
    ExecutorService workerExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("timestampClient-worker-%d").setDaemon(true).build());
    ExecutorService bossExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("timestampClient-boss-%d").setDaemon(true).build());

    HashedWheelTimer hwt = new HashedWheelTimer(new ThreadFactoryBuilder().setNameFormat("timestampClient-hashedWheelTimer-%d").setDaemon(true).build());
    factory = new NioClientSocketChannelFactory(bossExecutor, NETTY_BOSS_THREAD_COUNT, new NioWorkerPool(workerExecutor, NETTY_WORKER_THREAD_COUNT), hwt);

    bootstrap = new ClientBootstrap(factory);

    // If we end up needing to use one of the memory aware executors,
    // do so with code like this (leave commented out for reference).
    //
    // bootstrap.getPipeline().addLast("executor", new ExecutionHandler(
    // 	   new OrderedMemoryAwareThreadPoolExecutor(10 /* threads */, 1024*1024, 4*1024*1024)));

    bootstrap.getPipeline().addLast("decoder", new FixedLengthFrameDecoder(FIXED_MSG_RECEIVED_LENGTH));
    bootstrap.getPipeline().addLast("handler", this);

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    // bootstrap.setOption("connectTimeoutMillis", 120000);

    // Would be nice to try connecting here, but not sure if this works right. connectIfNeeded();

    try {
        registerJMX();
    } catch (Exception e) {
        SpliceLogUtils.error(LOG, "Unable to register TimestampClient with JMX. Timestamps will still be generated but metrics will not be available.");
    }
}
 
Example #29
Source File: NettyClient.java    From jstorm with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #30
Source File: NettyTcpClientTransport.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
NettyTcpClientTransport(TcpClientConfig config, Session session,
        NettyEventLoop loop) {
    // TODO check session.getAddress() instanceof IPAddress
    super(config, session);

    RpcMessageHandler handler = new RpcMessageHandler(session);

    bootstrap = new ClientBootstrap(loop.getClientFactory());
    bootstrap.setPipelineFactory(new StreamPipelineFactory(loop.getMessagePack(), handler));
    Map<String, Object> options = config.getOptions();
    setIfNotPresent(options, TCP_NO_DELAY, Boolean.TRUE, bootstrap);
    bootstrap.setOptions(options);
}