Java Code Examples for org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory

The following are top voted examples for showing how to use org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory. 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: java-codes   File: NettyTest.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    // Server服务启动器
    ServerBootstrap bootstrap = new ServerBootstrap(
            new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));
    // 设置一个处理客户端消息和各种消息事件的类(Handler)
    bootstrap
            .setPipelineFactory(new ChannelPipelineFactory() {
                @Override
                public ChannelPipeline getPipeline()
                        throws Exception {
                    return Channels
                            .pipeline(new HelloServerHandler());
                }
            });
    // 开放8000端口供客户端访问。
    bootstrap.bind(new InetSocketAddress(8000));
}
 
Example 2
Project: https-github.com-apache-zookeeper   File: NettyServerCnxnFactory.java   View source code 6 votes vote down vote up
NettyServerCnxnFactory() {
    bootstrap = new ServerBootstrap(
            new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));
    // parent channel
    bootstrap.setOption("reuseAddress", true);
    // child channels
    bootstrap.setOption("child.tcpNoDelay", true);
    /* set socket linger to off, so that socket close does not block */
    bootstrap.setOption("child.soLinger", -1);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline p = Channels.pipeline();
            if (secure) {
                initSSL(p);
            }
            p.addLast("servercnxnfactory", channelHandler);

            return p;
        }
    });
}
 
Example 3
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   View source code 6 votes vote down vote up
private ServerBootstrap startHttpServer(int port,
    final Token<DelegationTokenIdentifier> token, final URI url) {
  ServerBootstrap bootstrap = new ServerBootstrap(
      new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new HttpRequestDecoder(),
          new HttpChunkAggregator(65536), new HttpResponseEncoder(),
          new CredentialsLogicHandler(token, url.toString()));
    }
  });
  bootstrap.bind(new InetSocketAddress("localhost", port));
  return bootstrap;
}
 
Example 4
Project: abhot   File: TelnetServer.java   View source code 6 votes vote down vote up
@Override
public void start() throws KairosDBException
{
	// Configure the server.
	serverBootstrap = new ServerBootstrap(
			new NioServerSocketChannelFactory(
					Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("telnet-boss-%d").build()),
					Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("telnet-worker-%d").build())));

	// Configure the pipeline factory.
	serverBootstrap.setPipelineFactory(this);
	serverBootstrap.setOption("child.tcpNoDelay", true);
	serverBootstrap.setOption("child.keepAlive", true);
	serverBootstrap.setOption("reuseAddress", true);

	// Bind and start to accept incoming connections.
	serverBootstrap.bind(new InetSocketAddress(address, port));
}
 
Example 5
Project: graylog-plugin-beats   File: ConsolePrinter.java   View source code 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: bigstreams   File: ServerUtil.java   View source code 6 votes vote down vote up
/**
 * Startup a ServerBootstrap with NioServerSocketChannelFactory using the
 * portNo specified in the constructor.
 * 
 * @return
 */
public ServerBootstrap connect() {

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

	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			return Channels.pipeline(new MessageFrameDecoder(),  new MessageEventBagHandler(bagList));
		}
	});

	System.out.println("Binding to: localhost:" + portNo);
	bootstrap.bind(new InetSocketAddress("localhost", portNo));

	return bootstrap;

}
 
Example 7
Project: bigstreams   File: TestFilesSendWorker.java   View source code 6 votes vote down vote up
private ServerBootstrap connectServer(boolean simulateConflict,
		boolean simulateConflictErrorPointer) {

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

	final MessageEventBagHandler messagEventBagHandler = new MessageEventBagHandler(
			bagList, simulateConflict, simulateConflictErrorPointer);
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			return Channels.pipeline(new MessageFrameDecoder(),
					messagEventBagHandler);
		}
	});

	bootstrap.bind(new InetSocketAddress(testPort));

	return bootstrap;

}
 
Example 8
Project: bigstreams   File: TestFilesSendWorkerConflict.java   View source code 6 votes vote down vote up
private ServerBootstrap connectServer() {

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

		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new MessageFrameDecoder(),
						new MessageEventBagHandler(bagList));
			}
		});

		bootstrap.bind(new InetSocketAddress(testPort));

		return bootstrap;

	}
 
Example 9
Project: bigstreams   File: CollectorServerImpl.java   View source code 6 votes vote down vote up
@Override
public void connect() {

	workerService = createWorkerService(getThreadPoolType(CollectorProperties.WRITER.COLLECTOR_WORKER_THREAD_POOL));

	workerbossService = createWorkderBossService(getThreadPoolType(CollectorProperties.WRITER.COLLECTOR_WORKERBOSS_THREAD_POOL));
	channelFactory = new NioServerSocketChannelFactory(workerbossService,
			workerService);

	bootstrap = new ServerBootstrap(channelFactory);

	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			return Channels.pipeline(ipFilterHandler,
					new MessageFrameDecoder(), new ReadTimeoutHandler(
							HashedWheelTimerFactory.getInstance(),
							readTimeout, TimeUnit.MILLISECONDS),
					metricsHandler, channelHandler);
		}
	});

	bootstrap.bind(new InetSocketAddress(port));

}
 
Example 10
Project: bigstreams   File: CoordinationServerImpl.java   View source code 6 votes vote down vote up
/**
 * Startup a ServerBootstrap with NioServerSocketChannelFactory using the
 * portNo specified in the constructor.
 * 
 */
private void connectLockBootstrap() {

	lockBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
			Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool()));

	lockBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			return Channels.pipeline(new MessageFrameDecoder(),
					metricHandler, lockHandler);
		}
	});

	lockBootstrap.bind(new InetSocketAddress(lockPort));

}
 
Example 11
Project: bigstreams   File: CoordinationServerImpl.java   View source code 6 votes vote down vote up
/**
 * Startup a ServerBootstrap with NioServerSocketChannelFactory using the
 * portNo specified in the constructor.
 * 
 */
private void connectUnlockBootstrap() {

	unlockBootstrap = new ServerBootstrap(
			new NioServerSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	unlockBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			return Channels.pipeline(new MessageFrameDecoder(),
					unlockHandler);
		}
	});

	unlockBootstrap.bind(new InetSocketAddress(releaseLockPort));

}
 
Example 12
Project: big-c   File: TestDelegationTokenRemoteFetcher.java   View source code 6 votes vote down vote up
private ServerBootstrap startHttpServer(int port,
    final Token<DelegationTokenIdentifier> token, final URI url) {
  ServerBootstrap bootstrap = new ServerBootstrap(
      new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new HttpRequestDecoder(),
          new HttpChunkAggregator(65536), new HttpResponseEncoder(),
          new CredentialsLogicHandler(token, url.toString()));
    }
  });
  bootstrap.bind(new InetSocketAddress("localhost", port));
  return bootstrap;
}
 
Example 13
Project: incubator-omid   File: TSOChannelHandler.java   View source code 6 votes vote down vote up
@Inject
public TSOChannelHandler(TSOServerConfig config, RequestProcessor requestProcessor, MetricsRegistry metrics) {

    this.config = config;
    this.metrics = metrics;
    this.requestProcessor = requestProcessor;
    // Setup netty listener
    this.factory = new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("boss-%d").build()),
            Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("worker-%d").build()),
            (Runtime.getRuntime().availableProcessors() * 2 + 1) * 2);

    this.bootstrap = new ServerBootstrap(factory);
    bootstrap.setPipelineFactory(new TSOPipelineFactory(this));

}
 
Example 14
Project: incubator-omid   File: ProgrammableTSOServer.java   View source code 6 votes vote down vote up
@Inject
public ProgrammableTSOServer(int port) {
    // Setup netty listener
    factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(new ThreadFactoryBuilder()
            .setNameFormat("boss-%d").build()), Executors.newCachedThreadPool(new ThreadFactoryBuilder()
            .setNameFormat("worker-%d").build()), (Runtime.getRuntime().availableProcessors() * 2 + 1) * 2);

    // Create the global ChannelGroup
    channelGroup = new DefaultChannelGroup(ProgrammableTSOServer.class.getName());

    ServerBootstrap bootstrap = new ServerBootstrap(factory);
    bootstrap.setPipelineFactory(new TSOChannelHandler.TSOPipelineFactory(this));

    // Add the parent channel to the group
    Channel channel = bootstrap.bind(new InetSocketAddress(port));
    channelGroup.add(channel);

    LOG.info("********** Dumb TSO Server running on port {} **********", port);
}
 
Example 15
Project: OpenMobster   File: TextProtocolServer.java   View source code 6 votes vote down vote up
public void start()
{
	//Configure the server
	NioServerSocketChannelFactory nioFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
		Executors.newCachedThreadPool());
	ServerBootstrap bootstrap = new ServerBootstrap(nioFactory);
	
	// Configure the pipeline factory.
	bootstrap.setPipelineFactory(new TextProtocolPipelineFactory());
	
	//some more options
	bootstrap.setOption("child.tcpNoDelay", true);
       bootstrap.setOption("child.keepAlive", true);
	
	// Bind and start to accept incoming connections.
	this.channel = bootstrap.bind(new InetSocketAddress(1504));
	
	System.out.println("--------------------------------------------");
       System.out.println("Netty Http Server successfully loaded on port ("+1504+").....");
       System.out.println("--------------------------------------------");
}
 
Example 16
Project: fastcatsearch3   File: HttpTransportModule.java   View source code 6 votes vote down vote up
@Override
protected boolean doLoad() throws ModuleException {

	serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
			workerCount));

	serverBootstrap.setPipelineFactory(new MyChannelPipelineFactory(this));
	serverBootstrap.setOption("child.tcpNoDelay", tcpNoDelay);
	serverBootstrap.setOption("child.keepAlive", tcpKeepAlive);
	if (tcpSendBufferSize > 0) {
		serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize);
	}
	if (tcpReceiveBufferSize > 0) {
		serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize);
	}
	serverBootstrap.setOption("reuseAddress", reuseAddress);
	serverBootstrap.setOption("child.reuseAddress", reuseAddress);

	serverChannel = serverBootstrap.bind(new InetSocketAddress(port));
	logger.debug("Bound to port [{}]", port);

	return true;
}
 
Example 17
Project: opentsdb-flume   File: OpenTSDBSource.java   View source code 6 votes vote down vote up
@Override
public void start() {
  org.jboss.netty.channel.ChannelFactory factory = new NioServerSocketChannelFactory(
          Executors.newCachedThreadPool(), Executors.newCachedThreadPool());

  ServerBootstrap serverBootstrap = new ServerBootstrap(factory);
  serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() {
      EventHandler handler = new EventHandler();
      final ChannelPipeline pipeline = Channels.pipeline(handler);
      pipeline.addFirst("decoder", new LineBasedFrameDecoder(1024));
      pipeline.addLast("encoder", new StringEncoder(Charsets.UTF_8));
      return pipeline;
    }
  });

  logger.info("OpenTSDB Source starting...");

  if (host == null) {
    nettyChannel = serverBootstrap.bind(new InetSocketAddress(port));
  } else {
    nettyChannel = serverBootstrap.bind(new InetSocketAddress(host, port));
  }
  super.start();
}
 
Example 18
Project: dubbo-learning   File: NettyServer.java   View source code 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 19
Project: hadoop-2.6.0-cdh5.4.3   File: TestDelegationTokenRemoteFetcher.java   View source code 6 votes vote down vote up
private ServerBootstrap startHttpServer(int port,
    final Token<DelegationTokenIdentifier> token, final URI url) {
  ServerBootstrap bootstrap = new ServerBootstrap(
      new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new HttpRequestDecoder(),
          new HttpChunkAggregator(65536), new HttpResponseEncoder(),
          new CredentialsLogicHandler(token, url.toString()));
    }
  });
  bootstrap.bind(new InetSocketAddress("localhost", port));
  return bootstrap;
}
 
Example 20
Project: hadoop-EAR   File: NettyMapOutputHttpServer.java   View source code 6 votes vote down vote up
public synchronized void init(Configuration conf) {
    ThreadFactory bossFactory = new ThreadFactoryBuilder()
      .setNameFormat("ShuffleHandler Netty Boss #%d")
      .build();
  ThreadFactory workerFactory = new ThreadFactoryBuilder()
      .setNameFormat("ShuffleHandler Netty Worker #%d")
    .build();

  int maximumPoolSize = conf.getInt(MAXIMUM_THREAD_POOL_SIZE,
                                    DEFAULT_MAXIMUM_THREAD_POOL_SIZE);
  try {
    workerThreadPool =
      (ThreadPoolExecutor) Executors.newCachedThreadPool(workerFactory);
    workerThreadPool.setMaximumPoolSize(maximumPoolSize);
  } catch (ClassCastException e) {
    LOG.warn("Netty worker thread pool is not of type ThreadPoolExecutor", e);
  }
  LOG.info("Netty starting up with a maximum of " + maximumPoolSize +
      " worker threads");
  channelFactory = new NioServerSocketChannelFactory(
      Executors.newCachedThreadPool(bossFactory),
      workerThreadPool, maximumPoolSize);
}
 
Example 21
Project: anima   File: NettyServer.java   View source code 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 22
Project: dataworks-zeus   File: MasterServer.java   View source code 6 votes vote down vote up
public MasterServer(final ChannelHandler handler){
	NioServerSocketChannelFactory channelFactory=
		new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
	bootstrap=new ServerBootstrap(channelFactory);
	pipelineFactory=new ChannelPipelineFactory(){
		private final ProtobufVarint32LengthFieldPrepender frameEncoder = new ProtobufVarint32LengthFieldPrepender();
		private final ProtobufEncoder protobufEncoder = new ProtobufEncoder();
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline p = pipeline();
			p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
			p.addLast("protobufDecoder",new ProtobufDecoder(Protocol.SocketMessage.getDefaultInstance()));
			p.addLast("frameEncoder", frameEncoder);
			p.addLast("protobufEncoder", protobufEncoder);
			p.addLast("handler", handler);
			return p;
		}
		
	};
	try {
		bootstrap.setPipeline(pipelineFactory.getPipeline());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 23
Project: dataworks-zeus   File: MasterServer.java   View source code 6 votes vote down vote up
public MasterServer(final ChannelHandler handler){
	NioServerSocketChannelFactory channelFactory=
		new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
	bootstrap=new ServerBootstrap(channelFactory);
	pipelineFactory=new ChannelPipelineFactory(){
		private final ProtobufVarint32LengthFieldPrepender frameEncoder = new ProtobufVarint32LengthFieldPrepender();
		private final ProtobufEncoder protobufEncoder = new ProtobufEncoder();
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline p = pipeline();
			p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
			p.addLast("protobufDecoder",new ProtobufDecoder(Protocol.SocketMessage.getDefaultInstance()));
			p.addLast("frameEncoder", frameEncoder);
			p.addLast("protobufEncoder", protobufEncoder);
			p.addLast("handler", handler);
			return p;
		}
		
	};
	try {
		bootstrap.setPipeline(pipelineFactory.getPipeline());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 24
Project: graylog2-input-lumberjack   File: LumberjackServer.java   View source code 6 votes vote down vote up
public void start() {
    bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newFixedThreadPool(1),
            Executors.newCachedThreadPool()
    ));

    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = new DefaultChannelPipeline();
            pipeline.addLast("ssl", new SslHandler(getSSLEngine()));
            pipeline.addLast("decoder", new LumberjackDecoder());
            pipeline.addLast("logHandler", new LogEventHandler(eventListener));
            return pipeline;
        }
    });
    bootstrap.bind(new InetSocketAddress(configuration.getIpAddress(), configuration.getPort()));
}
 
Example 25
Project: hadoop-plus   File: ShuffleHandler.java   View source code 6 votes vote down vote up
@Override
protected void serviceInit(Configuration conf) throws Exception {
  manageOsCache = conf.getBoolean(SHUFFLE_MANAGE_OS_CACHE,
      DEFAULT_SHUFFLE_MANAGE_OS_CACHE);

  readaheadLength = conf.getInt(SHUFFLE_READAHEAD_BYTES,
      DEFAULT_SHUFFLE_READAHEAD_BYTES);
  
  maxShuffleConnections = conf.getInt(MAX_SHUFFLE_CONNECTIONS, 
                                      DEFAULT_MAX_SHUFFLE_CONNECTIONS);

  ThreadFactory bossFactory = new ThreadFactoryBuilder()
    .setNameFormat("ShuffleHandler Netty Boss #%d")
    .build();
  ThreadFactory workerFactory = new ThreadFactoryBuilder()
    .setNameFormat("ShuffleHandler Netty Worker #%d")
    .build();
  
  selector = new NioServerSocketChannelFactory(
      Executors.newCachedThreadPool(bossFactory),
      Executors.newCachedThreadPool(workerFactory));
  super.serviceInit(new Configuration(conf));
}
 
Example 26
Project: graylog-beats-plugin   File: LumberjackServer.java   View source code 6 votes vote down vote up
public void start() {
    bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newFixedThreadPool(1),
            Executors.newCachedThreadPool()
    ));

    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = new DefaultChannelPipeline();
            if(configuration.isSslEnabled()) {
                pipeline.addLast("ssl", new SslHandler(getSSLEngine()));
            }
            pipeline.addLast("decoder", new LumberjackDecoder());
            pipeline.addLast("logHandler", new EventHandler(eventListener));
            return pipeline;
        }
    });
    bootstrap.bind(new InetSocketAddress(configuration.getIpAddress(), configuration.getPort()));
}
 
Example 27
Project: FlexMap   File: TestDelegationTokenRemoteFetcher.java   View source code 6 votes vote down vote up
private ServerBootstrap startHttpServer(int port,
    final Token<DelegationTokenIdentifier> token, final URI url) {
  ServerBootstrap bootstrap = new ServerBootstrap(
      new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new HttpRequestDecoder(),
          new HttpChunkAggregator(65536), new HttpResponseEncoder(),
          new CredentialsLogicHandler(token, url.toString()));
    }
  });
  bootstrap.bind(new InetSocketAddress("localhost", port));
  return bootstrap;
}
 
Example 28
Project: tightrope   File: LoadBalancer.java   View source code 6 votes vote down vote up
public synchronized void start() {
    final Executor bossPool = Executors.newCachedThreadPool();
    final Executor workerPool = Executors.newCachedThreadPool();
    bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(bossPool, workerPool));
    final ClientSocketChannelFactory clientSocketChannelFactory = new NioClientSocketChannelFactory(bossPool, workerPool);
    bootstrap.setOption("child.tcpNoDelay", true);
    allChannels = new DefaultChannelGroup("handler");

    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(new FrontendHandler(allChannels, clientSocketChannelFactory, serverPool, statistics));
        }
    });

    log.info("Starting on port {}", port);
    acceptor = bootstrap.bind(new InetSocketAddress(port));

    if (acceptor.isBound()) {
        log.info("Server started successfully");
    }
}
 
Example 29
Project: zeus3   File: MasterServer.java   View source code 6 votes vote down vote up
public MasterServer(final ChannelHandler handler){
	NioServerSocketChannelFactory channelFactory=
		new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
	bootstrap=new ServerBootstrap(channelFactory);
	pipelineFactory=new ChannelPipelineFactory(){
		private final ProtobufVarint32LengthFieldPrepender frameEncoder = new ProtobufVarint32LengthFieldPrepender();
		private final ProtobufEncoder protobufEncoder = new ProtobufEncoder();
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline p = pipeline();
			p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
			p.addLast("protobufDecoder",new ProtobufDecoder(Protocol.SocketMessage.getDefaultInstance()));
			p.addLast("frameEncoder", frameEncoder);
			p.addLast("protobufEncoder", protobufEncoder);
			p.addLast("handler", handler);
			return p;
		}
		
	};
	try {
		bootstrap.setPipeline(pipelineFactory.getPipeline());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 30
Project: guagua   File: GuaguaAppMaster.java   View source code 6 votes vote down vote up
/**
 * Start rpc server which is used to update progress.
 */
private void startRPCServer() {
    this.rpcServer = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newFixedThreadPool(GuaguaYarnConstants.DEFAULT_STATUS_RPC_SERVER_THREAD_COUNT),
            Executors.newCachedThreadPool(new MasterThreadFactory())));

    // Set up the pipeline factory.
    this.rpcServer.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(new ObjectEncoder(),
                    new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())),
                    new ServerHandler());
        }
    });

    // Bind and start to accept incoming connections.
    this.rpcServer.bind(new InetSocketAddress(rpcPort));
}
 
Example 31
Project: incubator-tajo   File: PullServerAuxService.java   View source code 6 votes vote down vote up
@Override
public synchronized void init(Configuration conf) {
  try {
    manageOsCache = conf.getBoolean(SHUFFLE_MANAGE_OS_CACHE,
        DEFAULT_SHUFFLE_MANAGE_OS_CACHE);

    readaheadLength = conf.getInt(SHUFFLE_READAHEAD_BYTES,
        DEFAULT_SHUFFLE_READAHEAD_BYTES);

    ThreadFactory bossFactory = new ThreadFactoryBuilder()
        .setNameFormat("PullServerAuxService Netty Boss #%d")
        .build();
    ThreadFactory workerFactory = new ThreadFactoryBuilder()
        .setNameFormat("PullServerAuxService Netty Worker #%d")
        .build();

    selector = new NioServerSocketChannelFactory(
        Executors.newCachedThreadPool(bossFactory),
        Executors.newCachedThreadPool(workerFactory));

    localFS = new LocalFileSystem();
    super.init(new Configuration(conf));
  } catch (Throwable t) {
    LOG.error(t);
  }
}
 
Example 32
Project: tajo-cdh   File: PullServerAuxService.java   View source code 6 votes vote down vote up
@Override
public synchronized void init(Configuration conf) {
  try {
    manageOsCache = conf.getBoolean(SHUFFLE_MANAGE_OS_CACHE,
        DEFAULT_SHUFFLE_MANAGE_OS_CACHE);

    readaheadLength = conf.getInt(SHUFFLE_READAHEAD_BYTES,
        DEFAULT_SHUFFLE_READAHEAD_BYTES);

    ThreadFactory bossFactory = new ThreadFactoryBuilder()
        .setNameFormat("PullServerAuxService Netty Boss #%d")
        .build();
    ThreadFactory workerFactory = new ThreadFactoryBuilder()
        .setNameFormat("PullServerAuxService Netty Worker #%d")
        .build();

    selector = new NioServerSocketChannelFactory(
        Executors.newCachedThreadPool(bossFactory),
        Executors.newCachedThreadPool(workerFactory));

    localFS = new LocalFileSystem();
    super.init(new Configuration(conf));
  } catch (Throwable t) {
    LOG.error(t);
  }
}
 
Example 33
Project: hadoop-TCP   File: ShuffleHandler.java   View source code 6 votes vote down vote up
@Override
protected void serviceInit(Configuration conf) throws Exception {
  manageOsCache = conf.getBoolean(SHUFFLE_MANAGE_OS_CACHE,
      DEFAULT_SHUFFLE_MANAGE_OS_CACHE);

  readaheadLength = conf.getInt(SHUFFLE_READAHEAD_BYTES,
      DEFAULT_SHUFFLE_READAHEAD_BYTES);
  
  maxShuffleConnections = conf.getInt(MAX_SHUFFLE_CONNECTIONS, 
                                      DEFAULT_MAX_SHUFFLE_CONNECTIONS);

  ThreadFactory bossFactory = new ThreadFactoryBuilder()
    .setNameFormat("ShuffleHandler Netty Boss #%d")
    .build();
  ThreadFactory workerFactory = new ThreadFactoryBuilder()
    .setNameFormat("ShuffleHandler Netty Worker #%d")
    .build();
  
  selector = new NioServerSocketChannelFactory(
      Executors.newCachedThreadPool(bossFactory),
      Executors.newCachedThreadPool(workerFactory));
  super.serviceInit(new Configuration(conf));
}
 
Example 34
Project: remoterun   File: RemoteRunMaster.java   View source code 6 votes vote down vote up
/**
 * Creates a new RemoteRunMaster.
 *
 * @param bossExecutor the {@link Executor} which will execute the boss threads, see
 * {@link org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory(Executor, Executor)}
 * @param workerExecutor the {@link Executor} which will execute the I/O worker threads, see
 * {@link org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory(Executor, Executor)}
 * @param callback optional callback when agents connect/send messages
 */
public RemoteRunMaster(Executor bossExecutor, Executor workerExecutor, AgentConnectionCallback callback) {
  this.callback = callback;
  NioServerSocketChannelFactory factory = new NioServerSocketChannelFactory(bossExecutor, workerExecutor);
  bootstrap = new ServerBootstrap(factory);
  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(
        new SslHandler(createSslEngine()),

        new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4),
        new LengthFieldPrepender(4),

        new ProtobufDecoder(RemoteRun.AgentToMaster.getDefaultInstance()),
        new ProtobufEncoder(),

        new NettyLoggingHandler(),
        RemoteRunMaster.this
      );
    }
  });
  bootstrap.setOption("child.tcpNoDelay", true);
  bootstrap.setOption("child.keepAlive", true);
}
 
Example 35
Project: Cassandra-Wasef   File: Server.java   View source code 6 votes vote down vote up
private void run()
{
    // Configure the server.
    executionHandler = new ExecutionHandler(new RequestThreadPoolExecutor());
    factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
    ServerBootstrap bootstrap = new ServerBootstrap(factory);

    bootstrap.setOption("child.tcpNoDelay", true);

    // Set up the event pipeline factory.
    final EncryptionOptions.ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions();
    if (clientEnc.enabled)
    {
        logger.info("Enabling encrypted CQL connections between client and server");
        bootstrap.setPipelineFactory(new SecurePipelineFactory(this, clientEnc));
    }
    else
    {
        bootstrap.setPipelineFactory(new PipelineFactory(this));
    }

    // Bind and start to accept incoming connections.
    logger.info("Starting listening for CQL clients on {}...", socket);
    Channel channel = bootstrap.bind(socket);
    connectionTracker.allChannels.add(channel);
}
 
Example 36
Project: wso2-cassandra   File: Server.java   View source code 6 votes vote down vote up
private void run()
{
    // Configure the server.
    executionHandler = new ExecutionHandler(new RequestThreadPoolExecutor());
    factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
    ServerBootstrap bootstrap = new ServerBootstrap(factory);

    bootstrap.setOption("child.tcpNoDelay", true);

    // Set up the event pipeline factory.
    final EncryptionOptions.ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions();
    if (clientEnc.enabled)
    {
        logger.info("Enabling encrypted CQL connections between client and server");
        bootstrap.setPipelineFactory(new SecurePipelineFactory(this, clientEnc));
    }
    else
    {
        bootstrap.setPipelineFactory(new PipelineFactory(this));
    }

    // Bind and start to accept incoming connections.
    logger.info("Starting listening for CQL clients on {}...", socket);
    Channel channel = bootstrap.bind(socket);
    connectionTracker.allChannels.add(channel);
}
 
Example 37
Project: netty-servlet   File: NettyConnector.java   View source code 6 votes vote down vote up
@Override
public NettyConnector start() throws Exception {
    bootstrap = new ServerBootstrap(
            new NioServerSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new HttpServerPipelineFactory(getDispatcher()));

    bootstrap.setOption("child.tcpNoDelay", true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(new InetSocketAddress(getPort()));
    return this;
}
 
Example 38
Project: nettyProtobufChat   File: ChatServer.java   View source code 6 votes vote down vote up
public static void start(){
	// Configure the server.
       ServerBootstrap bootstrap = new ServerBootstrap(
               new NioServerSocketChannelFactory(
                       Executors.newCachedThreadPool(),
                       Executors.newCachedThreadPool()));

       // Set up the event pipeline factory.
       bootstrap.setPipelineFactory(new ChatServerPipelineFactory());

       // Bind and start to accept incoming connections.
       SocketAddress address = new InetSocketAddress(PORT);
       bootstrap.bind(address);
       logger.info("ChatServer start on ... "+address);
       ChatContext.start();
}
 
Example 39
Project: kairos-carbon   File: CarbonTextServer.java   View source code 6 votes vote down vote up
@Override
public void start() throws KairosDBException
{
	// Configure the server.
	m_serverBootstrap = new ServerBootstrap(
			new NioServerSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	// Configure the pipeline factory.
	m_serverBootstrap.setPipelineFactory(this);
	m_serverBootstrap.setOption("child.tcpNoDelay", true);
	m_serverBootstrap.setOption("child.keepAlive", true);
	m_serverBootstrap.setOption("reuseAddress", true);

	// Bind and start to accept incoming connections.
	m_serverBootstrap.bind(new InetSocketAddress(m_address, m_port));
}
 
Example 40
Project: kairos-carbon   File: CarbonPickleServer.java   View source code 6 votes vote down vote up
@Override
public void start() throws KairosDBException
{
	// Configure the server.
	m_serverBootstrap = new ServerBootstrap(
			new NioServerSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	// Configure the pipeline factory.
	m_serverBootstrap.setPipelineFactory(this);
	m_serverBootstrap.setOption("child.tcpNoDelay", true);
	m_serverBootstrap.setOption("child.keepAlive", true);
	m_serverBootstrap.setOption("reuseAddress", true);

	// Bind and start to accept incoming connections.
	m_serverBootstrap.bind(new InetSocketAddress(m_address, m_port));
}