當前位置: 首頁>>代碼示例>>Java>>正文


Java ClientBootstrap.connect方法代碼示例

本文整理匯總了Java中org.jboss.netty.bootstrap.ClientBootstrap.connect方法的典型用法代碼示例。如果您正苦於以下問題:Java ClientBootstrap.connect方法的具體用法?Java ClientBootstrap.connect怎麽用?Java ClientBootstrap.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.jboss.netty.bootstrap.ClientBootstrap的用法示例。


在下文中一共展示了ClientBootstrap.connect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: start

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
public void start(String ip, int port) {
	
	// Configure the client.
	System.setProperty("java.net.preferIPv4Stack", "true");  
       System.setProperty("java.net.preferIPv6Addresses", "false"); 
       bootstrap = new ClientBootstrap(
			new NioClientSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));
	// Set up the event pipeline factory.
	// bootstrap.setPipelineFactory(new MessageServerPipelineFactory());
	bootstrap.getPipeline().addLast("decoder", new PackageDecoder());
	bootstrap.getPipeline().addLast("encoder", new PackageEncoder());
	bootstrap.getPipeline().addLast("handler", new ClientHandler());
	
	bootstrap.setOption("tcpNoDelay", true);  
       bootstrap.setOption("keepAlive", true); 
       bootstrap.setOption("child.linger", 1);
       
	// Start the connection attempt.
	channelFuture = bootstrap.connect(new InetSocketAddress(ip, port));
	// Wait until the connection is closed or the connection attempt fails.
	channelFuture.awaitUninterruptibly();
	
	channel = channelFuture.awaitUninterruptibly().getChannel();
}
 
開發者ID:qizhenghao,項目名稱:HiBangClient,代碼行數:27,代碼來源:HiBangClient.java

示例2: run

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
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();
  }
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:24,代碼來源:SimpleTcpClient.java

示例3: connect

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
/**
  * 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);
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:28,代碼來源:BgpControllerImplTest.java

示例4: addNewSwitch

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
private void addNewSwitch(DummySwitch dummySwitch) {
	final SwitchChannelHandler switchHandler = new SwitchChannelHandler(coreConnector, aggreedVersion, moduleName);
	switchHandler.setDummySwitch(dummySwitch); // CONTAINS ALL THE INFO
												// ABOUT THIS SWITCH
	ChannelFactory factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool());
	ClientBootstrap bootstrap = new ClientBootstrap(factory);
	bootstrap.setOption("tcpNoDelay", true);
	bootstrap.setOption("keepAlive", true);
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() {
			return Channels.pipeline(switchHandler);
		}
	});

	// CONNECT AND ADD TO HASHMAP OF MANAGED SWITCHES
	ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 7753));
	managedSwitchesChannel.put(dummySwitch.getDatapathId(), future);
	managedBootstraps.put(dummySwitch.getDatapathId(), bootstrap);
	managedSwitches.put(dummySwitch.getDatapathId(), dummySwitch);
	switchHandler.registerSwitchConnection(future);
	switchHandler.setModuleHandler(moduleHandler);

}
 
開發者ID:fp7-netide,項目名稱:Engine,代碼行數:26,代碼來源:NetIdeModule.java

示例5: prepare

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
public void prepare(Map stormConf, TopologyContext context,
        			final OutputCollector collector) {
	_collector = collector;
	ChannelFactory factory = new NioClientSocketChannelFactory(
									Executors.newCachedThreadPool(),
									Executors.newCachedThreadPool());
	_bootstrap = new ClientBootstrap(factory);
	
	_bootstrap.setPipelineFactory(getPipelineFactory());
	_bootstrap.setOptions(_options);
	
    ChannelFuture future = _bootstrap.connect(new InetSocketAddress(_host, _port));
    
    int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
       Object connectTimeoutConfig = stormConf.get(Config.NIMBUS_TASK_LAUNCH_SECS);
       if (connectTimeoutConfig != null) {
       	connectTimeout = ((Number)connectTimeoutConfig).intValue()*1000/2;
       }
       
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isSuccess()) {
    	_bootstrap.releaseExternalResources();
    	throw new RuntimeException("Could not connect to '"+_host+":"+_port, future.getCause());
    }
    _channel = future.getChannel();  
}
 
開發者ID:danigiri,項目名稱:storm-sockets,代碼行數:27,代碼來源:SocketBolt.java

示例6: channelOpen

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {        
    final Channel inboundChannel = e.getChannel();
    RtmpProxy.ALL_CHANNELS.add(inboundChannel);
    inboundChannel.setReadable(false);        
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handshaker", new ProxyHandshakeHandler());
    cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));
    outboundChannel = f.getChannel();
    f.addListener(new ChannelFutureListener() {
        @Override public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                logger.info("connected to remote host: {}, port: {}", remoteHost, remotePort);
                inboundChannel.setReadable(true);
            } else {                    
                inboundChannel.close();
            }
        }
    });
}
 
開發者ID:bruni68510,項目名稱:flazr,代碼行數:22,代碼來源:ProxyHandler.java

示例7: testChannelConnectAndDisconnect

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
@Test
    public void testChannelConnectAndDisconnect() throws Exception {

        IsdnClientChannelFactory isdnClientFactory = new IsdnClientChannelFactory(Executors.newCachedThreadPool(),
                capiFactory, getConfigurator());
        ClientBootstrap client = new ClientBootstrap(isdnClientFactory);

        // CONNECT
        long c0 = System.currentTimeMillis();
        ChannelFuture channelFuture = client.connect(calledAddress, callingAddress);
        channelFuture.await(AWAIT_TIMEOUT);
        long c1 = System.currentTimeMillis();
        LOGGER.debug("testChannelConnectAndDisconnect() :: Connect performed in {}ms", (c1 - c0));

        // few delay to simulate a network application activity
//        Thread.sleep(10);

        // DISCONNECT
        long d0 = System.currentTimeMillis();
        ChannelFuture closeFuture = channelFuture.getChannel().close();
        closeFuture.await(AWAIT_TIMEOUT);
        long d1 = System.currentTimeMillis();
        LOGGER.debug("testChannelConnectAndDisconnect() :: Disconnect performed in {}ms", (d1 - d0));

    }
 
開發者ID:rmarins,項目名稱:netty-isdn-transport,代碼行數:26,代碼來源:IsdnClientChannelTest.java

示例8: createChannel

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
/**
 * Creates a new channel to given host and port.<br>
 *
 * @param host
 * @param port
 * @return
 * @throws Exception
 */
private Channel createChannel(String host, int port) throws Exception {
    // Important notice; use NioClientSocketChannelFactory instead
    // of NioServerSocketChannelFactory
    ChannelFactory channelFactory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
    ClientBootstrap bootstrap = new ClientBootstrap(channelFactory);
    //bootstrap.setPipelineFactory(new SipClientPipelineFactory(false,false));
    bootstrap.setPipelineFactory(new SipPipelineFactory(sipServerHandler));
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

    // open / connect to channel
    Channel c = future.await().getChannel();
    if (!future.isSuccess()) {
        log.warn(String.format("createChannel. Establishing connection failed[%s]",
                future.getCause().getMessage()));
        bootstrap.releaseExternalResources();
    }
    return c;
}
 
開發者ID:elasticsoftwarefoundation,項目名稱:elasterix,代碼行數:29,代碼來源:SipChannelFactoryImpl.java

示例9: channelOpen

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    logger.info("->");
    // 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.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));
    outboundChannel = f.getChannel();
    f.addListener(new ChannelFutureListener() {
        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();
            }
        }
    });
    logger.info("<-");
}
 
開發者ID:uli-heller,項目名稱:uli-mini-tools,代碼行數:26,代碼來源:HexDumpProxyInboundHandler.java

示例10: channelOpen

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
@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.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));
    outboundChannel = f.getChannel();
    f.addListener(new ChannelFutureListener() {
        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();
            }
        }
    });
}
 
開發者ID:uli-heller,項目名稱:uli-mini-tools,代碼行數:25,代碼來源:TextDumpProxyInboundHandler.java

示例11: main

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
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));
}
 
開發者ID:lihengming,項目名稱:java-codes,代碼行數:12,代碼來源:HelloClient.java

示例12: createClient

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) 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, key);
  bootstrap.setPipelineFactory(new NettyClientPipelineFactory(handler));
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort));
  future.awaitUninterruptibly(connectTimeout);
  if (!future.isDone()) {
    LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
  }
  if (future.isCancelled()) {
    LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
  }
  if (!future.isSuccess()) {
    LOGGER.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, key, connectTimeout);
  handler.setClient(client);
  return client;
}
 
開發者ID:leeyazhou,項目名稱:nfs-rpc,代碼行數:30,代碼來源:NettyClientFactory.java

示例13: testNettyChannelWriting

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
@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);
}
 
開發者ID:apache,項目名稱:incubator-omid,代碼行數:35,代碼來源:TestTSOChannelHandlerNetty.java

示例14: startClient

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
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();
  }
}
 
開發者ID:amitchmca,項目名稱:hadooparchitecturebook,代碼行數:39,代碼來源:EventClient.java

示例15: channelOpen

import org.jboss.netty.bootstrap.ClientBootstrap; //導入方法依賴的package包/類
@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();
		}
	});
}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:36,代碼來源:NetworkFailureHandler.java


注:本文中的org.jboss.netty.bootstrap.ClientBootstrap.connect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。