Java Code Examples for org.jboss.netty.channel.ChannelFactory

The following are top voted examples for showing how to use org.jboss.netty.channel.ChannelFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hadoop   File: SimpleTcpClient.java   Source Code and License 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 2
Project: athena   File: BgpControllerImplTest.java   Source Code and License 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 3
Project: athena   File: BgpControllerImplTest.java   Source Code and License 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 4
Project: aliyun-oss-hadoop-fs   File: SimpleTcpClient.java   Source Code and License 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 5
Project: graylog-plugin-beats   File: ConsolePrinter.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    String hostname = "127.0.0.1";
    int port = 5044;
    if (args.length >= 2) {
        hostname = args[0];
        port = firstNonNull(Ints.tryParse(args[1]), 5044);
    }
    if (args.length >= 1) {
        port = firstNonNull(Ints.tryParse(args[1]), 5044);
    }

    final ChannelFactory factory =
            new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool());
    final ServerBootstrap b = new ServerBootstrap(factory);
    b.getPipeline().addLast("beats-frame-decoder", new BeatsFrameDecoder());
    b.getPipeline().addLast("beats-codec", new BeatsCodecHandler());
    b.getPipeline().addLast("logging", new LoggingHandler());
    System.out.println("Starting listener on " + hostname + ":" + port);
    b.bind(new InetSocketAddress(hostname, port));
}
 
Example 6
Project: big-c   File: SimpleTcpClient.java   Source Code and License 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 7
Project: dubbo-learning   File: NettyServer.java   Source Code and License 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    //设置线程池(但是线程池中的线程都是守护线程,为的就是当JVM退出时候不用考虑守护线程是否已经结束)
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory); //Netty启动类
    //定义NettyHandler(这个应该是通用的Handler,只有在服务启动的时候生效一次)
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();

            pipeline.addLast("decoder", adapter.getDecoder()); //增加解码处理器
            pipeline.addLast("encoder", adapter.getEncoder()); //增加编码处理器
            pipeline.addLast("handler", nettyHandler); //增加具体操作的处理器
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 8
Project: hadoop-2.6.0-cdh5.4.3   File: SimpleTcpClient.java   Source Code and License 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 9
Project: anima   File: NettyServer.java   Source Code and License 6 votes vote down vote up
@Override
public void doOpen() throws Throwable {
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", false));
       ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
       int ioThread = conf.getInt(Constants.IO_THREADS,Constants.DEFAULT_IO_THREADS);
       ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, ioThread);
       bootstrap = new ServerBootstrap(channelFactory);
       
       final NettyHandler nettyHandler = new NettyHandler(getConf(), this);
       channels = nettyHandler.getChannels();
       bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
           public ChannelPipeline getPipeline() {
               NettyCodecAdapter adapter = new NettyCodecAdapter(conf,getCodec(), NettyServer.this);
               ChannelPipeline pipeline = Channels.pipeline();
               pipeline.addLast("decoder", adapter.getDecoder());
               pipeline.addLast("encoder", adapter.getEncoder());
               pipeline.addLast("handler", nettyHandler);
               return pipeline;
           }
       });
       // bind
       channel = bootstrap.bind(getBindAddress());
}
 
Example 10
Project: hadoop-plus   File: SimpleTcpClient.java   Source Code and License 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 11
Project: jstrom   File: NettyClientAsync.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
NettyClientAsync(Map storm_conf, ChannelFactory factory, ScheduledExecutorService scheduler, String host, int port, ReconnectRunnable reconnector) {
    super(storm_conf, factory, scheduler, host, port, reconnector);

    BATCH_THREASHOLD_WARN = ConfigExtension.getNettyBufferThresholdSize(storm_conf);
    blockSend = isBlockSend(storm_conf);
    directlySend = isDirectSend(storm_conf);

    flush_later = new AtomicBoolean(false);
    flushCheckInterval = Utils.getInt(storm_conf.get(Config.STORM_NETTY_FLUSH_CHECK_INTERVAL_MS), 10);

    Runnable flusher = new Runnable() {
        @Override
        public void run() {
            flush();
        }
    };
    long initialDelay = Math.min(1000, max_sleep_ms * max_retries);
    scheduler.scheduleAtFixedRate(flusher, initialDelay, flushCheckInterval, TimeUnit.MILLISECONDS);

    clientChannelFactory = factory;

    start();
    LOG.info(this.toString());
}
 
Example 12
Project: hops   File: SimpleTcpClient.java   Source Code and License 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
Project: tajo-cdh   File: NettyServerBase.java   Source Code and License 6 votes vote down vote up
public void init(ChannelPipelineFactory pipeline, int workerNum) {
  ChannelFactory factory = RpcChannelFactory.createServerChannelFactory(serviceName, workerNum);

  DefaultChannelFuture.setUseDeadLockChecker(false);

  pipelineFactory = pipeline;
  bootstrap = new ServerBootstrap(factory);
  bootstrap.setPipelineFactory(pipelineFactory);
  // TODO - should be configurable
  bootstrap.setOption("reuseAddress", true);
  bootstrap.setOption("child.tcpNoDelay", true);
  bootstrap.setOption("child.keepAlive", true);
  bootstrap.setOption("child.connectTimeoutMillis", 10000);
  bootstrap.setOption("child.connectResponseTimeoutMillis", 10000);
  bootstrap.setOption("child.receiveBufferSize", 1048576 * 10);
}
 
Example 14
Project: hadoop-TCP   File: SimpleTcpClient.java   Source Code and License 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 15
Project: storm-sockets   File: SocketBolt.java   Source Code and License 6 votes vote down vote up
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();  
}
 
Example 16
Project: hardfs   File: SimpleTcpClient.java   Source Code and License 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 17
Project: flazr   File: RtmpProxy.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {        

        Executor executor = Executors.newCachedThreadPool();
        ChannelFactory factory = new NioServerSocketChannelFactory(executor, executor);
        ServerBootstrap sb = new ServerBootstrap(factory);
        ClientSocketChannelFactory cf = new NioClientSocketChannelFactory(executor, executor);
        sb.setPipelineFactory(new ProxyPipelineFactory(cf,
                RtmpConfig.PROXY_REMOTE_HOST, RtmpConfig.PROXY_REMOTE_PORT));
        InetSocketAddress socketAddress = new InetSocketAddress(RtmpConfig.PROXY_PORT);
        sb.bind(socketAddress);
        logger.info("proxy server started, listening on {}", socketAddress);

        Thread monitor = new StopMonitor(RtmpConfig.PROXY_STOP_PORT);
        monitor.start();
        monitor.join();

        ChannelGroupFuture future = ALL_CHANNELS.close();
        logger.info("closing channels");
        future.awaitUninterruptibly();
        logger.info("releasing resources");
        factory.releaseExternalResources();
        logger.info("server stopped");

    }
 
Example 18
Project: hadoop-on-lustre2   File: SimpleTcpClient.java   Source Code and License 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 19
Project: Engine   File: NetIdeModule.java   Source Code and License 6 votes vote down vote up
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);

}
 
Example 20
Project: Engine   File: NetideModule.java   Source Code and License 6 votes vote down vote up
@Override
public void startUp(FloodlightModuleContext context) {
	//ADD SWITCH LISTENERS
	floodlightProvider.addOFSwitchListener(this);
	
	//REGISTER FOR MESSAGES FROM THE SWITCHES
	floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
	floodlightProvider.addOFMessageListener(OFType.PACKET_OUT, this);
	floodlightProvider.addOFMessageListener(OFType.FLOW_MOD, this);
       floodlightProvider.addOFMessageListener(OFType.ERROR, this);
       

       //START UP THE SERVER FOR THE ODL-SHIM
       ChannelFactory serverFactory = new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool());

       ServerBootstrap serverBootstrap = new ServerBootstrap(serverFactory);
       serverBootstrap.setOption("child.tcpNoDelay", true);
       serverBootstrap.setOption("child.keepAlive", true);
       serverBootstrap.setPipelineFactory(new NetIdePipelineFactory());
       logger.info("NetIDE Module binding to 41414..." );
       serverBootstrap.bind(new InetSocketAddress(41414)); //TODO: REMOVE HARD CODING
}
 
Example 21
Project: Engine   File: BackendChannelHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the comms channel to the SDN Controller and then adds a 
 * fake switch for the controller to manage
 * @param dummySwitch the switch to be managed
 */
private void addNewSwitch(DummySwitch dummySwitch) {
	final SwitchChannelHandler switchHandler = new SwitchChannelHandler();
	switchHandler.setDummySwitch(dummySwitch); //CONTAINS ALL THE INFO ABOUT THIS SWITCH
	switchHandler.setShimChannel(this.channel);
	
	
	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() {
        public ChannelPipeline getPipeline() {
            return Channels.pipeline(switchHandler);
        }
    });
    //CONNECT AND ADD TO HASHMAP OF MANAGED SWITCHES
    ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 6634));
    managedSwitches.put(dummySwitch.getId(), future);
    managedBootstraps.put(dummySwitch.getId(), bootstrap);
    switchHandler.setControllerChannel(future);
}
 
Example 22
Project: onos   File: BgpControllerImplTest.java   Source Code and License 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 23
Project: onos   File: BgpControllerImplTest.java   Source Code and License 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 24
Project: ApolloDev   File: Server.java   Source Code and License 6 votes vote down vote up
/**
 * Initialises the server.
 * 
 * @param releaseClassName The class name of the current active {@link Release}.
 * @throws ClassNotFoundException If the release class could not be found.
 * @throws IllegalAccessException If the release class could not be accessed.
 * @throws InstantiationException If the release class could not be instantiated.
 */
public void init(String releaseClassName) throws ClassNotFoundException, InstantiationException,
		IllegalAccessException {
	Class<?> clazz = Class.forName(releaseClassName);
	Release release = (Release) clazz.newInstance();

	logger.info("Initialized release #" + release.getReleaseNumber() + ".");

	ChannelFactory factory = new NioServerSocketChannelFactory(networkExecutor, networkExecutor);
	serviceBootstrap.setFactory(factory);
	httpBootstrap.setFactory(factory);
	jagGrabBootstrap.setFactory(factory);

	context = new ServerContext(release, serviceManager);
	ApolloHandler handler = new ApolloHandler(context);

	ChannelPipelineFactory servicePipelineFactory = new ServicePipelineFactory(handler, timer);
	serviceBootstrap.setPipelineFactory(servicePipelineFactory);

	ChannelPipelineFactory httpPipelineFactory = new HttpPipelineFactory(handler, timer);
	httpBootstrap.setPipelineFactory(httpPipelineFactory);

	ChannelPipelineFactory jagGrabPipelineFactory = new JagGrabPipelineFactory(handler, timer);
	jagGrabBootstrap.setPipelineFactory(jagGrabPipelineFactory);
}
 
Example 25
Project: elasterix   File: SipChannelFactoryImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 26
Project: httptunnel   File: HttpTunnelServerChannel.java   Source Code and License 6 votes vote down vote up
protected HttpTunnelServerChannel(ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, ServerSocketChannelFactory inboundFactory, ChannelGroup realConnections) {
	super(factory, pipeline, sink);

	tunnelIdPrefix = Long.toHexString(random.nextLong());
	tunnels = new ConcurrentHashMap<String, HttpTunnelAcceptedChannel>();

	config = new HttpTunnelServerChannelConfig();
	realChannel = inboundFactory.newChannel(this.createRealPipeline(realConnections));
	config.setRealChannel(realChannel);

	opened = new AtomicBoolean(true);
	bindState = new AtomicReference<BindState>(BindState.UNBOUND);

	realConnections.add(realChannel);

	Channels.fireChannelOpen(this);
}
 
Example 27
Project: EatDubbo   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 28
Project: dubbo2   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 29
Project: flume-release-1.7.0   File: SyslogTcpSource.java   Source Code and License 5 votes vote down vote up
@Override
public void start() {
  ChannelFactory factory = new NioServerSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool());

  ServerBootstrap serverBootstrap = new ServerBootstrap(factory);
  serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() {
      syslogTcpHandler handler = new syslogTcpHandler();
      handler.setEventSize(eventSize);
      handler.setFormater(formaterProp);
      handler.setKeepFields(keepFields);
      return Channels.pipeline(handler);
    }
  });

  logger.info("Syslog TCP Source starting...");

  if (host == null) {
    nettyChannel = serverBootstrap.bind(new InetSocketAddress(port));
  } else {
    nettyChannel = serverBootstrap.bind(new InetSocketAddress(host, port));
  }

  sourceCounter.start();
  super.start();
}
 
Example 30
Project: dubbox-hystrix   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 31
Project: athena   File: FpmManager.java   Source Code and License 5 votes vote down vote up
private void startServer() {
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(
            newCachedThreadPool(groupedThreads("onos/fpm", "sm-boss-%d")),
            newCachedThreadPool(groupedThreads("onos/fpm", "sm-worker-%d")));
    ChannelPipelineFactory pipelineFactory = () -> {
        // Allocate a new session per connection
        FpmSessionHandler fpmSessionHandler =
                new FpmSessionHandler(new InternalFpmListener());
        FpmFrameDecoder fpmFrameDecoder =
                new FpmFrameDecoder();

        // Setup the processing pipeline
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("FpmFrameDecoder", fpmFrameDecoder);
        pipeline.addLast("FpmSession", fpmSessionHandler);
        return pipeline;
    };

    InetSocketAddress listenAddress = new InetSocketAddress(FPM_PORT);

    serverBootstrap = new ServerBootstrap(channelFactory);
    serverBootstrap.setOption("child.reuseAddr", true);
    serverBootstrap.setOption("child.keepAlive", true);
    serverBootstrap.setOption("child.tcpNoDelay", true);
    serverBootstrap.setPipelineFactory(pipelineFactory);
    try {
        serverChannel = serverBootstrap.bind(listenAddress);
        allChannels.add(serverChannel);
    } catch (ChannelException e) {
        log.debug("Exception binding to FPM port {}: ",
                listenAddress.getPort(), e);
        stopServer();
    }
}
 
Example 32
Project: athena   File: BgpSessionManager.java   Source Code and License 5 votes vote down vote up
public void start() {
    log.debug("BGP Session Manager start.");
    isShutdown = false;

    ChannelFactory channelFactory = new NioServerSocketChannelFactory(
            newCachedThreadPool(groupedThreads("onos/bgp", "sm-boss-%d")),
            newCachedThreadPool(groupedThreads("onos/bgp", "sm-worker-%d")));
    ChannelPipelineFactory pipelineFactory = () -> {
        // Allocate a new session per connection
        BgpSession bgpSessionHandler =
                new BgpSession(BgpSessionManager.this);
        BgpFrameDecoder bgpFrameDecoder =
                new BgpFrameDecoder(bgpSessionHandler);

        // Setup the processing pipeline
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("BgpFrameDecoder", bgpFrameDecoder);
        pipeline.addLast("BgpSession", bgpSessionHandler);
        return pipeline;
    };
    InetSocketAddress listenAddress =
            new InetSocketAddress(bgpPort);

    serverBootstrap = new ServerBootstrap(channelFactory);
    // serverBootstrap.setOptions("reuseAddr", true);
    serverBootstrap.setOption("child.keepAlive", true);
    serverBootstrap.setOption("child.tcpNoDelay", true);
    serverBootstrap.setPipelineFactory(pipelineFactory);
    try {
        serverChannel = serverBootstrap.bind(listenAddress);
        allChannels.add(serverChannel);
    } catch (ChannelException e) {
        log.debug("Exception binding to BGP port {}: ",
                  listenAddress.getPort(), e);
    }
}
 
Example 33
Project: dubbocloud   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 34
Project: dubbos   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 35
Project: dubbo-comments   File: NettyServer.java   Source Code and License 5 votes vote down vote up
/**
 * 打开netty通道 并设置参数
 * @see com.alibaba.dubbo.remoting.transport.AbstractServer#doOpen()
 */
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    // workerCount默认Cpu核数+1
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    //所有handler的调用链
    //NettyHandler->NettyServer->MultiMessageHandler->HeartbeatHandler->(SPI,default is ALL)Dispatcher.dispatch()
    //->DecodeHandler->HeaderExchangeHandler->DubboProtocol.requestHandler
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 36
Project: dubbox   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 37
Project: dubbo   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 38
Project: incubator-omid   File: TSOClientRaw.java   Source Code and License 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 39
Project: dubbo3   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(() -> {
        NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
        ChannelPipeline pipeline = Channels.pipeline();
        /*int idleTimeout = getIdleTimeout();
        if (idleTimeout > 10000) {
            pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
        }*/
        pipeline.addLast("decoder", adapter.getDecoder());
        pipeline.addLast("encoder", adapter.getEncoder());
        pipeline.addLast("handler", nettyHandler);
        return pipeline;
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 40
Project: DubboCode   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 41
Project: jahhan   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 42
Project: dubbo2study   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 43
Project: jstorm-0.9.6.3-   File: NettyClientAsync.java   Source Code and License 5 votes vote down vote up
NettyClientAsync(Map storm_conf, ChannelFactory factory,
		ScheduledExecutorService scheduler, String host, int port,
		ReconnectRunnable reconnector) {
	super(storm_conf, factory, scheduler, host, port, reconnector);

	BATCH_THREASHOLD_WARN = ConfigExtension
			.getNettyBufferThresholdSize(storm_conf);

	blockSend = isBlockSend(storm_conf);

	directlySend = isDirectSend(storm_conf);

	flush_later = new AtomicBoolean(false);
	flushCheckInterval = Utils.getInt(
			storm_conf.get(Config.STORM_NETTY_FLUSH_CHECK_INTERVAL_MS), 10);

	Runnable flusher = new Runnable() {
		@Override
		public void run() {
			flush();
		}
	};
	long initialDelay = Math.min(1000, max_sleep_ms * max_retries);
	scheduler.scheduleWithFixedDelay(flusher, initialDelay,
			flushCheckInterval, TimeUnit.MILLISECONDS);

	clientChannelFactory = factory;

	start();

	LOG.info(this.toString());
}
 
Example 44
Project: parallec   File: TcpMeta.java   Source Code and License 5 votes vote down vote up
public TcpMeta(String command, int tcpPort, int tcpConnectTimeoutMillis,
        int tcpIdleTimeoutSec,
        ChannelFactory channelFactory) {
    super();
    this.command = command;
    this.tcpPort = tcpPort;
    this.tcpConnectTimeoutMillis = tcpConnectTimeoutMillis;
    this.tcpIdleTimeoutSec = tcpIdleTimeoutSec;
    this.channelFactory = channelFactory;
    
}
 
Example 45
Project: dubbo-comments   File: NettyServer.java   Source Code and License 5 votes vote down vote up
/**
 * 打开netty通道 并设置参数
 * @see com.alibaba.dubbo.remoting.transport.AbstractServer#doOpen()
 */
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    // workerCount默认Cpu核数+1
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    //所有handler的调用链
    //NettyHandler->NettyServer->MultiMessageHandler->HeartbeatHandler->(SPI,default is ALL)Dispatcher.dispatch()
    //->DecodeHandler->HeaderExchangeHandler->DubboProtocol.requestHandler
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 46
Project: learn_jstorm   File: NettyClientAsync.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
NettyClientAsync(Map storm_conf, ChannelFactory factory,
		ScheduledExecutorService scheduler, String host, int port,
		ReconnectRunnable reconnector) {
	super(storm_conf, factory, scheduler, host, port, reconnector);

	BATCH_THREASHOLD_WARN = ConfigExtension
			.getNettyBufferThresholdSize(storm_conf);

	blockSend = isBlockSend(storm_conf);

	directlySend = isDirectSend(storm_conf);

	flush_later = new AtomicBoolean(false);
	flushCheckInterval = Utils.getInt(
			storm_conf.get(Config.STORM_NETTY_FLUSH_CHECK_INTERVAL_MS), 10);

	Runnable flusher = new Runnable() {
		@Override
		public void run() {
			flush();
		}
	};
	long initialDelay = Math.min(1000, max_sleep_ms * max_retries);
	scheduler.scheduleWithFixedDelay(flusher, initialDelay,
			flushCheckInterval, TimeUnit.MILLISECONDS);

	clientChannelFactory = factory;

	start();

	LOG.info(this.toString());
}
 
Example 47
Project: dubbo-ex   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 48
Project: jstrom   File: NettyClientSync.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
NettyClientSync(Map storm_conf, ChannelFactory factory, ScheduledExecutorService scheduler, String host, int port, ReconnectRunnable reconnector) {
    super(storm_conf, factory, scheduler, host, port, reconnector);

    batchQueue = new ConcurrentLinkedQueue<MessageBatch>();

    WaitStrategy waitStrategy = (WaitStrategy) Utils.newInstance((String) storm_conf.get(Config.TOPOLOGY_DISRUPTOR_WAIT_STRATEGY));

    disruptorQueue = DisruptorQueue.mkInstance(name, ProducerType.MULTI, MAX_SEND_PENDING * 8, waitStrategy);
    disruptorQueue.consumerStarted();

    if (connectMyself == false) {
        registerSyncMetrics();
    }

    Runnable trigger = new Runnable() {
        @Override
        public void run() {
            trigger();
        }
    };

    scheduler.scheduleAtFixedRate(trigger, 10, 1, TimeUnit.SECONDS);

    /**
     * In sync mode, it can't directly use common factory, it will occur problem when client close and restart
     */
    ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + JStormServerUtils.getName(host, port) + "-boss");
    bossExecutor = Executors.newCachedThreadPool(bossFactory);
    ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + JStormServerUtils.getName(host, port) + "-worker");
    workerExecutor = Executors.newCachedThreadPool(workerFactory);

    clientChannelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor, 1);

    start();

    LOG.info(this.toString());
}
 
Example 49
Project: BlockJump-HighscoreServer   File: Server.java   Source Code and License 5 votes vote down vote up
public Server(int i) throws IOException, SQLException {
    try {
        sqlManager = new SQLManager("root", password());
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    DEBUG = debug();
    packetHandler = new PacketHandler(sqlManager);
    new Thread(packetHandler).start();

    ChannelFactory factory = new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
    ServerBootstrap bootstrap = new ServerBootstrap(factory);

    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            return Channels.pipeline(new ServerHandler(packetHandler));
        }
    });

    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.bind(new InetSocketAddress(i));

    Log.log("Server started on port " + i + ".", MessageState.ENGINE);

    new HighscoreScript(sqlManager);
}
 
Example 50
Project: Tstream   File: NettyClientAsync.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
NettyClientAsync(Map storm_conf, ChannelFactory factory,
		ScheduledExecutorService scheduler, String host, int port,
		ReconnectRunnable reconnector) {
	super(storm_conf, factory, scheduler, host, port, reconnector);

	BATCH_THREASHOLD_WARN = ConfigExtension
			.getNettyBufferThresholdSize(storm_conf);

	blockSend = isBlockSend(storm_conf);

	directlySend = isDirectSend(storm_conf);

	flush_later = new AtomicBoolean(false);
	flushCheckInterval = Utils.getInt(
			storm_conf.get(Config.STORM_NETTY_FLUSH_CHECK_INTERVAL_MS), 10);

	Runnable flusher = new Runnable() {
		@Override
		public void run() {
			flush();
		}
	};
	long initialDelay = Math.min(1000, max_sleep_ms * max_retries);
	scheduler.scheduleWithFixedDelay(flusher, initialDelay,
			flushCheckInterval, TimeUnit.MILLISECONDS);

	clientChannelFactory = factory;

	start();

	LOG.info(this.toString());
}
 
Example 51
Project: LetUsGo-Server   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 52
Project: teiid   File: SocketListener.java   Source Code and License 5 votes vote down vote up
/**
   * 
   * @param port
   * @param inputBufferSize
   * @param outputBufferSize
   * @param engine null if SSL is disabled
   * @param bindaddress
   * @param server
   */
  public SocketListener(InetSocketAddress address, int inputBufferSize,
	int outputBufferSize, int maxWorkers, SSLConfiguration config, ClientServiceRegistryImpl csr, StorageManager storageManager) {
  	if (config != null) {
  		this.isClientEncryptionEnabled = config.isClientEncryptionEnabled();
  	}
  	this.csr = csr;

  	this.nettyPool = Executors.newCachedThreadPool(new NamedThreadFactory("NIO")); //$NON-NLS-1$
      if (LogManager.isMessageToBeRecorded(LogConstants.CTX_TRANSPORT, MessageLevel.DETAIL)) { 
          LogManager.logDetail(LogConstants.CTX_TRANSPORT, "server = " + address.getAddress() + "binding to port:" + address.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
}
      
      if (maxWorkers == 0) {
      	maxWorkers = Math.max(4, 2*Runtime.getRuntime().availableProcessors());
      }

      ChannelFactory factory = new NioServerSocketChannelFactory(this.nettyPool, this.nettyPool, maxWorkers);
      
      bootstrap = new ServerBootstrap(factory);
      this.channelHandler = createChannelPipelineFactory(config, storageManager);
      bootstrap.setPipelineFactory(channelHandler);
      if (inputBufferSize != 0) {
      	bootstrap.setOption("receiveBufferSize", new Integer(inputBufferSize)); //$NON-NLS-1$
      }
      if (outputBufferSize != 0) {
      	bootstrap.setOption("sendBufferSize", new Integer(outputBufferSize)); //$NON-NLS-1$
      }
      bootstrap.setOption("keepAlive", Boolean.TRUE); //$NON-NLS-1$
      
      this.serverChanel = bootstrap.bind(address);
  }
 
Example 53
Project: incubator-tajo   File: NettyServerBase.java   Source Code and License 5 votes vote down vote up
public void init(ChannelPipelineFactory pipeline, int workerNum) {
  ChannelFactory factory = RpcChannelFactory.createServerChannelFactory(serviceName, workerNum);

  pipelineFactory = pipeline;
  bootstrap = new ServerBootstrap(factory);
  bootstrap.setPipelineFactory(pipelineFactory);
  // TODO - should be configurable
  bootstrap.setOption("reuseAddress", true);
  bootstrap.setOption("child.tcpNoDelay", true);
  bootstrap.setOption("child.keepAlive", true);
  bootstrap.setOption("child.connectTimeoutMillis", 10000);
  bootstrap.setOption("child.connectResponseTimeoutMillis", 10000);
  bootstrap.setOption("child.receiveBufferSize", 1048576 * 10);
}
 
Example 54
Project: incubator-storm   File: Client.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
Client(Map storm_conf, ChannelFactory factory, String host, int port) {
    this.factory = factory;
    message_queue = new LinkedBlockingQueue<Object>();
    retries = new AtomicInteger(0);
    channelRef = new AtomicReference<Channel>(null);
    being_closed = new AtomicBoolean(false);
    wait_for_requests = false;

    // Configure
    buffer_size = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_BUFFER_SIZE));
    max_retries = Math.min(30, Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_MAX_RETRIES)));
    base_sleep_ms = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_MIN_SLEEP_MS));
    max_sleep_ms = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_MAX_SLEEP_MS));

    bootstrap = new ClientBootstrap(factory);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("sendBufferSize", buffer_size);
    bootstrap.setOption("keepAlive", true);

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

    // Start the connection attempt.
    remote_addr = new InetSocketAddress(host, port);
    bootstrap.connect(remote_addr);
}
 
Example 55
Project: piggybank-squeal   File: NettyMetricsTransport.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(Map props) {
	super.initialize(props);
	
	// Pull the destination host and port.
	String host = props.get(NETTY_HOST_KEY).toString();
	Object p_string = props.get(NETTY_PORT_KEY);
	int port = DEFAULT_PORT;
	if (p_string != null) {
		port = Integer.parseInt(p_string.toString());
	}
		
	// Connect and pull the channel.
	ChannelFactory factory =
			new NioClientSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool());

	ClientBootstrap bootstrap = new ClientBootstrap(factory);

	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() {
			return Channels.pipeline(
					new StringEncoder(CharsetUtil.UTF_8), 
					new SimpleChannelHandler());
		}
	});

	bootstrap.setOption("keepAlive", true);

	ChannelFuture f = bootstrap.connect(new InetSocketAddress(host, port));
	
	f.awaitUninterruptibly();
	if (!f.isSuccess()) {
		throw new RuntimeException("Initialization failed.", f.getCause());
	}
	
	channel = f.getChannel();
}
 
Example 56
Project: exDubbo   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 57
Project: storm-sockets   File: EchoServer.java   Source Code and License 5 votes vote down vote up
public EchoServer(int port) {
	_port = port;
	ChannelFactory factory = new NioServerSocketChannelFactory(
									Executors.newCachedThreadPool(),
									Executors.newCachedThreadPool());
			 
	_bootstrap = new ServerBootstrap(factory);
	_bootstrap.setOption("reuseAddress", true);
	_bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() {
			return Channels.pipeline(new EchoServerHandler());
		}
	});
}
 
Example 58
Project: rest4j   File: HttpNettyServer.java   Source Code and License 5 votes vote down vote up
@Override
  public void start()
  {
    ChannelFactory factory =
          new NioServerSocketChannelFactory(
                  Executors.newCachedThreadPool(),
                  Executors.newFixedThreadPool(_threadPoolSize)
//                  Executors.newCachedThreadPool()
          );

    _bootstrap = new ServerBootstrap(factory);
    _bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
      @Override
      public ChannelPipeline getPipeline() throws Exception
      {
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("rapi", new RAPServerCodec());
        pipeline.addLast("execution", _executionHandler);
        pipeline.addLast("handler", new Handler());
        return pipeline;
      }
    });
    _bootstrap.bind(new InetSocketAddress(_port));
  }
 
Example 59
Project: incubator-twill   File: TrackerService.java   Source Code and License 5 votes vote down vote up
@Override
protected void startUp() throws Exception {
  Executor bossThreads = Executors.newFixedThreadPool(NUM_BOSS_THREADS,
                                                      new ThreadFactoryBuilder()
                                                        .setDaemon(true)
                                                        .setNameFormat("boss-thread")
                                                        .build());

  Executor workerThreads = Executors.newCachedThreadPool(new ThreadFactoryBuilder()
                                                           .setDaemon(true)
                                                           .setNameFormat("worker-thread#%d")
                                                           .build());

  ChannelFactory factory = new NioServerSocketChannelFactory(bossThreads, workerThreads);

  bootstrap = new ServerBootstrap(factory);

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    public ChannelPipeline getPipeline() {
      ChannelPipeline pipeline = Channels.pipeline();

      pipeline.addLast("decoder", new HttpRequestDecoder());
      pipeline.addLast("aggregator", new HttpChunkAggregator(MAX_INPUT_SIZE));
      pipeline.addLast("encoder", new HttpResponseEncoder());
      pipeline.addLast("compressor", new HttpContentCompressor());
      pipeline.addLast("handler", new ReportHandler(resourceReport));

      return pipeline;
    }
  });

  Channel channel = bootstrap.bind(new InetSocketAddress(host, 0));
  bindAddress = (InetSocketAddress) channel.getLocalAddress();
  url = URI.create(String.format("http://%s:%d", host, bindAddress.getPort())).toURL();
  channelGroup.add(channel);
}
 
Example 60
Project: dangdangdotcom   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}