org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory Java Examples

The following examples show how to use org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: ControllerConnector.java    From FlowSpaceFirewall with Apache License 2.0 5 votes vote down vote up
public ControllerConnector(){
	proxies = new HashMap<Long, List<Proxy>>();

	channelCreator = new NioClientSocketChannelFactory(
               Executors.newCachedThreadPool(),
               Executors.newCachedThreadPool(), workerThreads);
	timer = new HashedWheelTimer();
	
}
 
Example #11
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 #12
Source File: HttpClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
private static NettyAsyncHttpProviderConfig createConfig() {

      final NettyAsyncHttpProviderConfig nettyConfig = new NettyAsyncHttpProviderConfig();
      final NioClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory();

      nettyConfig.setSocketChannelFactory(channelFactory);
      nettyConfig.setChunkedFileChunkSize(CHUNKED_FILE_CHUNK_SIZE);

      final HashedWheelTimer timer = new HashedWheelTimer();
      timer.start();
      nettyConfig.setNettyTimer(timer);

      registerShutdownHook(channelFactory, timer);
      return nettyConfig;
    }
 
Example #13
Source File: HttpClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
private static void registerShutdownHook(final NioClientSocketChannelFactory channelFactory,
                                         final HashedWheelTimer hashedWheelTimer) {

  Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
      channelFactory.shutdown();
      channelFactory.releaseExternalResources();
      hashedWheelTimer.stop();
    }
  });
}
 
Example #14
Source File: ClientChannelFactory.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public ChannelFactory createChannelFactory(int bossCount, int workerCount, Timer timer) {
    ExecutorService boss = newCachedThreadPool("Pinpoint-Client-Boss");
    BossPool bossPool = new NioClientBossPool(boss, bossCount, timer, ThreadNameDeterminer.CURRENT);

    ExecutorService worker = newCachedThreadPool("Pinpoint-Client-Worker");
    WorkerPool workerPool = new NioWorkerPool(worker, workerCount, ThreadNameDeterminer.CURRENT);
    return new NioClientSocketChannelFactory(bossPool, workerPool);
}
 
Example #15
Source File: NetworkFailuresProxy.java    From flink with Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

	// Set up the event pipeline factory.
	ClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(executor, executor);
	serverBootstrap.setOption("child.tcpNoDelay", true);
	serverBootstrap.setOption("child.keepAlive", true);
	serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();

			// synchronized for a race between blocking and creating new handlers
			synchronized (networkFailureHandlers) {
				NetworkFailureHandler failureHandler = new NetworkFailureHandler(
					blocked,
					networkFailureHandler -> networkFailureHandlers.remove(networkFailureHandler),
					channelFactory,
					remoteHost,
					remotePort);
				networkFailureHandlers.add(failureHandler);
				pipeline.addLast(NETWORK_FAILURE_HANDLER_NAME, failureHandler);
			}
			return pipeline;
		}
	});
	channel = serverBootstrap.bind(new InetSocketAddress(localPort));

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example #16
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 #17
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 #18
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 #19
Source File: NetworkFailuresProxy.java    From flink with Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

	// Set up the event pipeline factory.
	ClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(executor, executor);
	serverBootstrap.setOption("child.tcpNoDelay", true);
	serverBootstrap.setOption("child.keepAlive", true);
	serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();

			// synchronized for a race between blocking and creating new handlers
			synchronized (networkFailureHandlers) {
				NetworkFailureHandler failureHandler = new NetworkFailureHandler(
					blocked,
					networkFailureHandler -> networkFailureHandlers.remove(networkFailureHandler),
					channelFactory,
					remoteHost,
					remotePort);
				networkFailureHandlers.add(failureHandler);
				pipeline.addLast(NETWORK_FAILURE_HANDLER_NAME, failureHandler);
			}
			return pipeline;
		}
	});
	channel = serverBootstrap.bind(new InetSocketAddress(localPort));

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example #20
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 #21
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
	super(new HashedWheelTimer(), 0, 0, config.getIdleConnectionTimeoutInMs(), TimeUnit.MILLISECONDS) ;
	socketChannelFactory = new NioClientSocketChannelFactory(
			Executors.newCachedThreadPool(),
			config.executorService());
	bootstrap = new ClientBootstrap(socketChannelFactory);
	this.config = config;
}
 
Example #22
Source File: TcpUdpSshPingResourceStore.java    From parallec with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize; cached threadpool is safe as it is releasing resources automatically if idle
 */
public synchronized void init() {
    channelFactory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());

    datagramChannelFactory = new NioDatagramChannelFactory(
            Executors.newCachedThreadPool());

    timer = new HashedWheelTimer();
}
 
Example #23
Source File: NettySend.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
public void connect(){

		bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory(
				Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool()));
		bootstrap.setOption("tcpNoDelay", false);
		bootstrap.setOption("keepAlive", true);

		final NettyClientHandler handler = new NettyClientHandler(this, timer);
		
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline =  Channels.pipeline();
				pipeline.addLast("handler", handler);
				pipeline.addLast("encoder", new StringEncoder());
				return pipeline;
			}
		});
		
		bootstrap.setOption("remoteAddress", new InetSocketAddress(host, port));
		try {
			ChannelFuture future = bootstrap.connect().sync();
			channel = future.getChannel();
		} catch (Exception e) {
			logger.error(ExceptionUtil.getErrorMessage(e));
			bootstrap.releaseExternalResources();
			System.exit(-1);//第一次连接出现异常直接退出,不走重连
		}
	}
 
Example #24
Source File: TSOClientRaw.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
public TSOClientRaw(String host, int port) throws InterruptedException, ExecutionException {
    // Start client with Nb of active threads = 3 as maximum.
    ChannelFactory factory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()), 3);
    // Create the bootstrap
    ClientBootstrap bootstrap = new ClientBootstrap(factory);

    InetSocketAddress addr = new InetSocketAddress(host, port);

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder",
            new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder",
            new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());

    Handler handler = new Handler();
    pipeline.addLast("handler", handler);

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

    ChannelFuture channelFuture = bootstrap.connect(addr).await();
    channel = channelFuture.getChannel();
}
 
Example #25
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static ClientBootstrap createClientBootstrap(
		FileClientPipelineFactory clientPipelineFactory) {
	ClientBootstrap bootstrap = new ClientBootstrap(
			new NioClientSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	bootstrap.setPipelineFactory(clientPipelineFactory);

	return bootstrap;
}
 
Example #26
Source File: HelloClient.java    From java-codes with MIT License 5 votes vote down vote up
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));
}
 
Example #27
Source File: NetworkFailuresProxy.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

	// Set up the event pipeline factory.
	ClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(executor, executor);
	serverBootstrap.setOption("child.tcpNoDelay", true);
	serverBootstrap.setOption("child.keepAlive", true);
	serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();

			// synchronized for a race between blocking and creating new handlers
			synchronized (networkFailureHandlers) {
				NetworkFailureHandler failureHandler = new NetworkFailureHandler(
					blocked,
					networkFailureHandler -> networkFailureHandlers.remove(networkFailureHandler),
					channelFactory,
					remoteHost,
					remotePort);
				networkFailureHandlers.add(failureHandler);
				pipeline.addLast(NETWORK_FAILURE_HANDLER_NAME, failureHandler);
			}
			return pipeline;
		}
	});
	channel = serverBootstrap.bind(new InetSocketAddress(localPort));

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example #28
Source File: TcpProviderPoc.java    From parallec with Apache License 2.0 4 votes vote down vote up
public void request() throws Exception {
    
    // Parse options.
    String host = "localhost";
    int port = 10081;
    int connectTimeoutMillis = 2000;
    // Configure the client.
    ClientBootstrap bootstrap = new ClientBootstrap(
            new NioClientSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));

    final TelnetClientHandler handler = new TelnetClientHandler();

    // Configure the pipeline factory.
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("framer", new DelimiterBasedFrameDecoder(1024,
                    Delimiters.lineDelimiter()));
            pipeline.addLast("stringDecoder", stringDecoder);
            pipeline.addLast("stringEncoder", stringEncoder);
            pipeline.addLast("handler", handler);
            return pipeline;
        }
    });
    
    
    bootstrap.setOption("connectTimeoutMillis",connectTimeoutMillis);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
            port));

    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().getChannel();
    // Read commands from the stdin.
    ChannelFuture lastWriteFuture = null;
    String command = "hadoopMonitorFromClient";

    // Sends the line to server.
    lastWriteFuture = channel.write(command + "\r\n");

    // Wait until all messages are flushed before closing the channel.
    if (lastWriteFuture != null) {
        lastWriteFuture.await();
    }

    // note that we need to wait for the response before

    // wait time before close the channel too early that msg will not be
    // received.

    while (!handler.channelCompleted) {
        Thread.sleep(1l);
    }

    // Close the connection. Make sure the close operation ends because
    // all I/O operations are asynchronous in Netty.
    channel.close().awaitUninterruptibly();
    // Shut down all thread pools to exit.
    bootstrap.releaseExternalResources();
    
}
 
Example #29
Source File: TSOClient.java    From phoenix-omid with Apache License 2.0 4 votes vote down vote up
private TSOClient(OmidClientConfiguration omidConf) throws IOException {

        // Start client with Nb of active threads = 3 as maximum.
        int tsoExecutorThreads = omidConf.getExecutorThreads();

        factory = new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(
                        new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
                Executors.newCachedThreadPool(
                        new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()), tsoExecutorThreads);
        // Create the bootstrap
        bootstrap = new ClientBootstrap(factory);

        requestTimeoutInMs = omidConf.getRequestTimeoutInMs();
        requestMaxRetries = omidConf.getRequestMaxRetries();
        tsoReconnectionDelayInSecs = omidConf.getReconnectionDelayInSecs();

        LOG.info("Connecting to TSO...");
        HostAndPort hp;
        switch (omidConf.getConnectionType()) {
            case HA:
                zkClient = ZKUtils.initZKClient(omidConf.getConnectionString(),
                                                omidConf.getZkNamespace(),
                                                omidConf.getZkConnectionTimeoutInSecs());
                zkCurrentTsoPath = omidConf.getZkCurrentTsoPath();
                configureCurrentTSOServerZNodeCache(zkCurrentTsoPath);
                String tsoInfo = getCurrentTSOInfoFoundInZK(zkCurrentTsoPath);
                // TSO info includes the new TSO host:port address and epoch
                String[] currentTSOAndEpochArray = tsoInfo.split("#");
                hp = HostAndPort.fromString(currentTSOAndEpochArray[0]);
                setTSOAddress(hp.getHostText(), hp.getPort());
                epoch = Long.parseLong(currentTSOAndEpochArray[1]);
                LOG.info("\t* Current TSO host:port found in ZK: {} Epoch {}", hp, getEpoch());
                break;
            case DIRECT:
            default:
                hp = HostAndPort.fromString(omidConf.getConnectionString());
                setTSOAddress(hp.getHostText(), hp.getPort());
                LOG.info("\t* TSO host:port {} will be connected directly", hp);
                break;
        }

        fsmExecutor = Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder().setNameFormat("tsofsm-%d").build());
        fsm = new StateMachine.FsmImpl(fsmExecutor);
        fsm.setInitState(new DisconnectedState(fsm));

        ChannelPipeline pipeline = bootstrap.getPipeline();
        pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
        pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
        pipeline.addLast("protobufdecoder", new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
        pipeline.addLast("protobufencoder", new ProtobufEncoder());
        pipeline.addLast("handler", new Handler(fsm));

        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);
        bootstrap.setOption("reuseAddress", true);
        bootstrap.setOption("connectTimeoutMillis", 100);
        lowLatency = false;



        conflictDetectionLevel = omidConf.getConflictAnalysisLevel();

    }
 
Example #30
Source File: BgpSessionManagerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Starts up the BGP peer and connects it to the tested BgpSessionManager
 * instance.
 *
 * @param connectToSocket the socket to connect to
 */
private void connect(InetSocketAddress connectToSocket)
    throws InterruptedException {
    //
    // Setup the BGP Peer, i.e., the "remote" BGP router that will
    // initiate the BGP connection, send BGP UPDATE messages, etc.
    //
    ChannelFactory channelFactory =
        new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());
    ChannelPipelineFactory pipelineFactory = () -> {
        // Setup the transmitting pipeline
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("TestBgpPeerFrameDecoder",
                peerFrameDecoder);
        pipeline.addLast("TestBgpPeerChannelHandler",
                peerChannelHandler);
        return pipeline;
    };

    peerBootstrap = new ClientBootstrap(channelFactory);
    peerBootstrap.setOption("child.keepAlive", true);
    peerBootstrap.setOption("child.tcpNoDelay", true);
    peerBootstrap.setPipelineFactory(pipelineFactory);
    peerBootstrap.connect(connectToSocket);

    boolean result;
    // Wait until the OPEN message is received
    result = peerFrameDecoder.receivedOpenMessageLatch.await(
        MESSAGE_TIMEOUT_MS,
        TimeUnit.MILLISECONDS);
    assertThat(result, is(true));
    // Wait until the KEEPALIVE message is received
    result = peerFrameDecoder.receivedKeepaliveMessageLatch.await(
        MESSAGE_TIMEOUT_MS,
        TimeUnit.MILLISECONDS);
    assertThat(result, is(true));

    for (BgpSession bgpSession : bgpSessionManager.getBgpSessions()) {
        if (bgpSession.remoteInfo().bgpId().equals(BGP_PEER1_ID)) {
            bgpSession1 = bgpSession;
        }
        if (bgpSession.remoteInfo().bgpId().equals(BGP_PEER2_ID)) {
            bgpSession2 = bgpSession;
        }
        if (bgpSession.remoteInfo().bgpId().equals(BGP_PEER3_ID)) {
            bgpSession3 = bgpSession;
        }
    }
}