Java Code Examples for org.jboss.netty.bootstrap.ClientBootstrap#connect()

The following examples show how to use org.jboss.netty.bootstrap.ClientBootstrap#connect() . 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: 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 2
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 3
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 4
Source File: TestTSOChannelHandlerNetty.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10_000)
public void testNettyChannelWriting() throws Exception {

    // ------------------------------------------------------------------------------------------------------------
    // Prepare test
    // ------------------------------------------------------------------------------------------------------------

    // Connect channel handler
    channelHandler.reconnect();
    // Create client and connect it
    ClientBootstrap nettyClient = createNettyClientBootstrap();
    ChannelFuture channelF = nettyClient.connect(new InetSocketAddress("localhost", 1434));
    // Basic checks for connection
    while (!channelF.isDone()) /** do nothing */ ;
    assertTrue(channelF.isSuccess());
    assertTrue(channelF.getChannel().isConnected());
    Channel channel = channelF.getChannel();
    // Eventually the channel group of the server should have 2 elements
    while (channelHandler.channelGroup.size() != 2) /** do nothing */ ;
    // Write first handshake request
    TSOProto.HandshakeRequest.Builder handshake = TSOProto.HandshakeRequest.newBuilder();
    // NOTE: Add here the required handshake capabilities when necessary
    handshake.setClientCapabilities(TSOProto.Capabilities.newBuilder().build());
    channelF.getChannel().write(TSOProto.Request.newBuilder().setHandshakeRequest(handshake.build()).build());

    // ------------------------------------------------------------------------------------------------------------
    // Test channel writing
    // ------------------------------------------------------------------------------------------------------------
    testWritingTimestampRequest(channel);

    testWritingCommitRequest(channel);

    testWritingFenceRequest(channel);
}
 
Example 5
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 6
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 7
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 8
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 9
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 10
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static void createThumbPicture(ClientBootstrap bootstrap,
		String host, int port, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new CreateThumbPictureClientHandler(
			host, uri, userName, pwd, filePath);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 11
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static void replaceFile(ClientBootstrap bootstrap, String host,
		int port, File file, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new ReplaceFileClientHandler(host, uri,
			filePath, file, userName, pwd);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 12
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static void deleteFile(ClientBootstrap bootstrap, String host,
		int port, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new DeleteFileClientHandler(host, uri,
			filePath, userName, pwd);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 13
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static void uploadFile(ClientBootstrap bootstrap, String host,
		int port, File file, String fileName, String thumbMark,
		String userName, String pwd) {
	//1.构建uri对象
	URI uri = getUri(host, port);
	//2.连接netty服务端
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	//3.异步获取Channel对象
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}
	//4.初始化文件上传句柄对象
	WrapFileClientHandler handler = new UploadFileClientHandler(host, uri,
			file, fileName, thumbMark, userName, pwd);
	//5.获取Request对象
	HttpRequest request = handler.getRequest();
	//6.获取Http数据处理工厂
	HttpDataFactory factory = getHttpDataFactory();
	//7.进行数据的包装处理,主要是进行上传文件所需要的参数的设置,此时调用的句柄是具体的UploadFileClientHandler对象
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	//8.把request写到管道中,传输给服务端
	channel.write(request);
	//9.做一些关闭资源的动作
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();

	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 14
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 15
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 16
Source File: TestTSOChannelHandlerNetty.java    From phoenix-omid with Apache License 2.0 4 votes vote down vote up
@Test(timeOut = 10_000)
public void testNettyConnectionToTSOFromClient() throws Exception {

    ClientBootstrap nettyClient = createNettyClientBootstrap();

    ChannelFuture channelF = nettyClient.connect(new InetSocketAddress("localhost", 1434));

    // ------------------------------------------------------------------------------------------------------------
    // Test the client can't connect cause the server is not there
    // ------------------------------------------------------------------------------------------------------------
    while (!channelF.isDone()) /** do nothing */ ;
    assertFalse(channelF.isSuccess());

    // ------------------------------------------------------------------------------------------------------------
    // Test creation of a server connection
    // ------------------------------------------------------------------------------------------------------------
    channelHandler.reconnect();
    assertTrue(channelHandler.listeningChannel.isOpen());
    // Eventually the channel group of the server should contain the listening channel
    assertEquals(channelHandler.channelGroup.size(), 1);

    // ------------------------------------------------------------------------------------------------------------
    // Test that a client can connect now
    // ------------------------------------------------------------------------------------------------------------
    channelF = nettyClient.connect(new InetSocketAddress("localhost", 1434));
    while (!channelF.isDone()) /** do nothing */ ;
    assertTrue(channelF.isSuccess());
    assertTrue(channelF.getChannel().isConnected());
    // Eventually the channel group of the server should have 2 elements
    while (channelHandler.channelGroup.size() != 2) /** do nothing */ ;

    // ------------------------------------------------------------------------------------------------------------
    // Close the channel on the client side and test we have one element less in the channel group
    // ------------------------------------------------------------------------------------------------------------
    channelF.getChannel().close().await();
    // Eventually the channel group of the server should have only one element
    while (channelHandler.channelGroup.size() != 1) /** do nothing */ ;

    // ------------------------------------------------------------------------------------------------------------
    // Open a new channel and test the connection closing on the server side through the channel handler
    // ------------------------------------------------------------------------------------------------------------
    channelF = nettyClient.connect(new InetSocketAddress("localhost", 1434));
    while (!channelF.isDone()) /** do nothing */ ;
    assertTrue(channelF.isSuccess());
    // Eventually the channel group of the server should have 2 elements again
    while (channelHandler.channelGroup.size() != 2) /** do nothing */ ;
    channelHandler.closeConnection();
    assertFalse(channelHandler.listeningChannel.isOpen());
    assertEquals(channelHandler.channelGroup.size(), 0);
    // Wait some time and check the channel was closed
    TimeUnit.SECONDS.sleep(1);
    assertFalse(channelF.getChannel().isOpen());

    // ------------------------------------------------------------------------------------------------------------
    // Test server re-connections with connected clients
    // ------------------------------------------------------------------------------------------------------------
    // Connect first time
    channelHandler.reconnect();
    assertTrue(channelHandler.listeningChannel.isOpen());
    // Eventually the channel group of the server should contain the listening channel
    assertEquals(channelHandler.channelGroup.size(), 1);
    // Check the client can connect
    channelF = nettyClient.connect(new InetSocketAddress("localhost", 1434));
    while (!channelF.isDone()) /** do nothing */ ;
    assertTrue(channelF.isSuccess());
    // Eventually the channel group of the server should have 2 elements
    while (channelHandler.channelGroup.size() != 2) /** do nothing */ ;
    // Re-connect and check that client connection was gone
    channelHandler.reconnect();
    assertTrue(channelHandler.listeningChannel.isOpen());
    // Eventually the channel group of the server should contain the listening channel
    assertEquals(channelHandler.channelGroup.size(), 1);
    // Wait some time and check the channel was closed
    TimeUnit.SECONDS.sleep(1);
    assertFalse(channelF.getChannel().isOpen());

    // ------------------------------------------------------------------------------------------------------------
    // Test closeable interface with re-connection trial
    // ------------------------------------------------------------------------------------------------------------
    channelHandler.close();
    assertFalse(channelHandler.listeningChannel.isOpen());
    assertEquals(channelHandler.channelGroup.size(), 0);
}
 
Example 17
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 18
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;
        }
    }
}