Java Code Examples for org.jboss.netty.bootstrap.ServerBootstrap#setOption()

The following examples show how to use org.jboss.netty.bootstrap.ServerBootstrap#setOption() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Controller.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tell controller that we're ready to accept pcc connections.
 */
public void run() {
    try {
        final ServerBootstrap bootstrap = createServerBootStrap();

        bootstrap.setOption("reuseAddr", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);

        ChannelPipelineFactory pfact = new PcepPipelineFactory(this);

        bootstrap.setPipelineFactory(pfact);
        InetSocketAddress sa = new InetSocketAddress(pcepPort);
        cg = new DefaultChannelGroup();
        cg.add(bootstrap.bind(sa));
        log.debug("Listening for PCC connection on {}", sa);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 2
Source File: AbstractAsyncServer.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Configure the bootstrap before it get bound
 */
protected void configureBootstrap(ServerBootstrap bootstrap) {
    // Bind and start to accept incoming connections.
    bootstrap.setOption("backlog", backlog);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("child.tcpNoDelay", true);
}
 
Example 3
Source File: CarbonPickleServer.java    From kairos-carbon with Apache License 2.0 5 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));


	m_udpBootstrap = new ConnectionlessBootstrap(
			new NioDatagramChannelFactory());

	m_udpBootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(m_maxSize));

	m_udpBootstrap.setPipelineFactory(this);

	m_udpBootstrap.bind(new InetSocketAddress(m_port));

}
 
Example 4
Source File: BgpSessionManager.java    From onos with Apache License 2.0 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", log)),
            newCachedThreadPool(groupedThreads("onos/bgp", "sm-worker-%d", log)));
    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 5
Source File: TimestampServer.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public void startServer() {

        ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("TimestampServer-%d").setDaemon(true).build());
        this.factory = new NioServerSocketChannelFactory(executor, executor);

        SpliceLogUtils.info(LOG, "Timestamp Server starting (binding to port %s)...", port);

        ServerBootstrap bootstrap = new ServerBootstrap(factory);

        // If we end up needing to use one of the memory aware executors,
        // do so with code like this (leave commented out for reference).
        // But for now we can use the 'lite' implementation.
        //
        // final ThreadPoolExecutor pipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor(
        //     5 /* threads */, 1048576, 1073741824,
        //     100, TimeUnit.MILLISECONDS, // Default would have been 30 SECONDS
        //     Executors.defaultThreadFactory());
        // bootstrap.setPipelineFactory(new TimestampPipelineFactory(pipelineExecutor, handler));

        bootstrap.setPipelineFactory(new TimestampPipelineFactoryLite(handler));

        bootstrap.setOption("tcpNoDelay", true);
        // bootstrap.setOption("child.sendBufferSize", 1048576);
        // bootstrap.setOption("child.receiveBufferSize", 1048576);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.setOption("child.reuseAddress", true);
        // bootstrap.setOption("child.connectTimeoutMillis", 120000);

        this.channel = bootstrap.bind(new InetSocketAddress(getPortNumber()));

        SpliceLogUtils.info(LOG, "Timestamp Server started.");
    }
 
Example 6
Source File: EventReviewServer.java    From hadoop-arch-book with Apache License 2.0 5 votes vote down vote up
public void startServer() throws Exception {

    eventProcessor = EventProcessor.initAndStartEventProcess(config, flumePorts, useCheckPut);

    handler = new EventServerHandler();

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

    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.receiveBufferSize", 1048576);
    bootstrap.setOption("child.sendBufferSize", 1048576);

    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
      public ChannelPipeline getPipeline() {
        ChannelPipeline p = Channels.pipeline();
        p.addLast("batch", handler);
        return p;
      }
    });

    LOG.info("EventReviewServer: binding to :" + portNumber);
    channel = bootstrap.bind(new InetSocketAddress(portNumber));

    LOG.info("EventReviewServer: bound to :" + portNumber + " " + channel.isBound() + " " + channel.getLocalAddress());


  }
 
Example 7
Source File: NettyServerBase.java    From incubator-tajo with Apache License 2.0 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 8
Source File: ProxyServer.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
public FutureTask<ProxyServer> run() {
    FutureTask<ProxyServer> future = new FutureTask<>(new Callable<ProxyServer>() {

        @Override
        public ProxyServer call() throws Exception {
            // Configure the server.
            bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
            FiltersChangeNotifier changeNotifier = filtersChangeNotifier != null ? filtersChangeNotifier : FiltersChangeNotifier.IGNORE;
            CommonHttpPipeline pipelineFactory = new CommonHttpPipeline(TIMER);
            changeNotifier.addFiltersListener(pipelineFactory);
            bootstrap.setPipelineFactory(pipelineFactory);

            bootstrap.setOption("child.tcpNoDelay", true);
            bootstrap.setOption("child.connectTimeoutMillis", 2000);
            /*bootstrap.setOption("child.writeBufferHighWaterMark", true);
            bootstrap.setOption("child.writeBufferLowWaterMark", true);
            bootstrap.setOption("child.writeSpinCount", true);*/
            bootstrap.setOption("child.receiveBufferSizePredictor", new AdaptiveReceiveBufferSizePredictor());

            channel = bootstrap.bind(new InetSocketAddress(port));
            LOG.info("server bound to port {}", port);

            LOG.info("current handlers registred {}", pipelineFactory.getPipeline().getNames());

            return ProxyServer.this;
        }
    });

    final Thread thread = new Thread(future, "Proxy Server");
    thread.start();
    return future;
}
 
Example 9
Source File: NetworkFailuresProxy.java    From flink with Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

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

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

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example 10
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
@Override
protected void serviceStart() throws Exception {
  Configuration conf = getConfig();
  userRsrc = new ConcurrentHashMap<String,String>();
  secretManager = new JobTokenSecretManager();
  recoverState(conf);
  ServerBootstrap bootstrap = new ServerBootstrap(selector);
  // Timer is shared across entire factory and must be released separately
  timer = new HashedWheelTimer();
  try {
    pipelineFact = new HttpPipelineFactory(conf, timer);
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
  bootstrap.setOption("backlog", conf.getInt(SHUFFLE_LISTEN_QUEUE_SIZE,
      DEFAULT_SHUFFLE_LISTEN_QUEUE_SIZE));
  bootstrap.setOption("child.keepAlive", true);
  bootstrap.setPipelineFactory(pipelineFact);
  port = conf.getInt(SHUFFLE_PORT_CONFIG_KEY, DEFAULT_SHUFFLE_PORT);
  Channel ch = bootstrap.bind(new InetSocketAddress(port));
  accepted.add(ch);
  port = ((InetSocketAddress)ch.getLocalAddress()).getPort();
  conf.set(SHUFFLE_PORT_CONFIG_KEY, Integer.toString(port));
  pipelineFact.SHUFFLE.setPort(port);
  LOG.info(getName() + " listening on port " + port);
  super.serviceStart();

  sslFileBufferSize = conf.getInt(SUFFLE_SSL_FILE_BUFFER_SIZE_KEY,
                                  DEFAULT_SUFFLE_SSL_FILE_BUFFER_SIZE);
  connectionKeepAliveEnabled =
      conf.getBoolean(SHUFFLE_CONNECTION_KEEP_ALIVE_ENABLED,
        DEFAULT_SHUFFLE_CONNECTION_KEEP_ALIVE_ENABLED);
  connectionKeepAliveTimeOut =
      Math.max(1, conf.getInt(SHUFFLE_CONNECTION_KEEP_ALIVE_TIME_OUT,
        DEFAULT_SHUFFLE_CONNECTION_KEEP_ALIVE_TIME_OUT));
  mapOutputMetaInfoCacheSize =
      Math.max(1, conf.getInt(SHUFFLE_MAPOUTPUT_META_INFO_CACHE_SIZE,
        DEFAULT_SHUFFLE_MAPOUTPUT_META_INFO_CACHE_SIZE));
}
 
Example 11
Source File: MongoServer.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public void startServer() {

        if ( ( properties != null ) && ( Boolean
                .parseBoolean( properties.getProperty( "usergrid.mongo.disable", "false" ) ) ) ) {
            logger.info( "Usergrid Mongo Emulation Server Disabled" );
            return;
        }

        logger.info( "Starting Usergrid Mongo Emulation Server" );

        if ( realm != null ) {
            securityManager = new DefaultSecurityManager( realm );
        }

        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool() ) );

        bootstrap.setOption( "child.bufferFactory", HeapChannelBufferFactory.getInstance( ByteOrder.LITTLE_ENDIAN ) );

        // Set up the pipeline factory.
        ExecutionHandler executionHandler =
                new ExecutionHandler( new OrderedMemoryAwareThreadPoolExecutor( 16, 1048576, 1048576 ) );
        // TODO if config'ed for SSL, start the SslMSPF instead, change port as well?
        bootstrap.setPipelineFactory(
                new MongoServerPipelineFactory( emf, smf, management, securityManager, executionHandler ) );

        // Bind and start to accept incoming connections.
        channel = bootstrap.bind( new InetSocketAddress( 27017 ) );

        logger.info( "Usergrid Mongo API Emulation Server accepting connections..." );
    }
 
Example 12
Source File: HttpServer.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
public synchronized void run() {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    b.setPipelineFactory(new CommonHttpPipeline(TIMER));
    b.setOption("child.tcpNoDelay", true);
    channel = b.bind(new InetSocketAddress(port));
    LOG.info("server bound to port {}", port);
}
 
Example 13
Source File: MemCacheDaemon.java    From fqueue with Apache License 2.0 5 votes vote down vote up
/**
 * Bind the network connection and start the network processing threads.
 */
public void start() {
	// TODO provide tweakable options here for passing in custom executors.
	channelFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors
			.newCachedThreadPool());

	allChannels = new DefaultChannelGroup("jmemcachedChannelGroup");

	ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);

	ChannelPipelineFactory pipelineFactory;
	if (binary)
		pipelineFactory = createMemcachedBinaryPipelineFactory(cache, memcachedVersion, verbose, idleTime,
				allChannels);
	else
		pipelineFactory = createMemcachedPipelineFactory(cache, memcachedVersion, verbose, idleTime, frameSize,
				allChannels);

	bootstrap.setOption("child.tcpNoDelay", true);
	bootstrap.setOption("child.keepAlive", true);
	bootstrap.setOption("child.receiveBufferSize", 1024 * 64);
	bootstrap.setPipelineFactory(pipelineFactory);

	Channel serverChannel = bootstrap.bind(addr);
	allChannels.add(serverChannel);

	log.info("Listening on " + String.valueOf(addr.getHostName()) + ":" + addr.getPort());

	running = true;
}
 
Example 14
Source File: NettyServer.java    From recipes-rss with Apache License 2.0 5 votes vote down vote up
/**
 * Builds and starts netty
 */
public NettyServer build() {
	PipelineFactory factory = new PipelineFactory(handlers, encoder,
			decoder, numBossThreads);

	ThreadPoolExecutor bossPool = new ThreadPoolExecutor(
			numBossThreads, numBossThreads, 60, TimeUnit.SECONDS,
			new LinkedBlockingQueue<Runnable>(),
			new DescriptiveThreadFactory("Boss-Thread"));

	ThreadPoolExecutor workerPool = new ThreadPoolExecutor(
			numWorkerThreads, numWorkerThreads, 60, TimeUnit.SECONDS,
			new LinkedBlockingQueue<Runnable>(),
			new DescriptiveThreadFactory("Worker-Thread"));

	ChannelFactory nioServer = new NioServerSocketChannelFactory(
			bossPool, workerPool, numWorkerThreads);

	ServerBootstrap serverBootstrap = new ServerBootstrap(nioServer);
	serverBootstrap.setOption("reuseAddress", true);
	serverBootstrap.setOption("keepAlive", true);
	serverBootstrap.setPipelineFactory(factory);

	Channel serverChannel = serverBootstrap.bind(new InetSocketAddress(
			host, port));
	logger.info("Started netty server {}:{}", host, port);

	NettyServer server = new NettyServer();
	server.addChannel(serverChannel);

	return server;
}
 
Example 15
Source File: Netty.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void emit() {
	// TODO Auto-generated method stub
	// Server服务启动器
	try {
		 bossExecutor = Executors.newCachedThreadPool();
		 workerExecutor = Executors.newCachedThreadPool();
		 bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						bossExecutor,workerExecutor));
		final NettyServerHandler nettyServerHandler = new NettyServerHandler(
				this);
		// 设置一个处理客户端消息和各种消息事件的类(Handler)
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				if(isExtract){
					pipeline.addLast("zlibDecoder", new ZlibDecoder(ZlibWrapper.GZIP));
				}
				pipeline.addLast(
						"decoder",
						new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
								false, true, ChannelBuffers.copiedBuffer(
										delimiter,
										Charset.forName(encoding))));
				pipeline.addLast("handler", nettyServerHandler);
				return pipeline;
			}
		});
		bootstrap.setOption("child.receiveBufferSize", receiveBufferSize); 
		bootstrap.setOption("child.keepAlive", true);
		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host),
				port));
	} catch (Exception e) {
		logger.error(e.getMessage());
		System.exit(1);
	}
}
 
Example 16
Source File: NettyRev.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
public void startup(){
        try {
            bossExecutor = Executors.newCachedThreadPool();
            workerExecutor = Executors.newCachedThreadPool();
            bootstrap = new ServerBootstrap(
                    new NioServerSocketChannelFactory(
                            bossExecutor,workerExecutor));
            final NettyServerHandler nettyServerHandler = new NettyServerHandler();
            // 设置一个处理客户端消息和各种消息事件的类(Handler)
            bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                @Override
                public ChannelPipeline getPipeline() throws Exception {
                    ChannelPipeline pipeline = Channels.pipeline();
                    pipeline.addLast(
                            "decoder",
                            new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
                                    false, true, ChannelBuffers.copiedBuffer(
                                    delimiter,
                                    Charset.forName(encoding))));
                    pipeline.addLast("handler", nettyServerHandler);
                    return pipeline;
                }
            });
            bootstrap.setOption("child.receiveBufferSize", receiveBufferSize);
            bootstrap.setOption("child.keepAlive", true);
//            bootstrap.setOption("child.tcpNoDelay", true);
            bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host),
                    port));
            logger.warn("netty server start up success port:{}.", port);
        } catch (Exception e) {
            logger.error(e.getMessage());
            System.exit(1);
        }
    }
 
Example 17
Source File: PinpointServerAcceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void setOptions(ServerBootstrap bootstrap) {
    // is read/write timeout necessary? don't need it because of NIO?
    // write timeout should be set through additional interceptor. write
    // timeout exists.

    // tcp setting
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.keepAlive", true);
    // buffer setting
    bootstrap.setOption("child.sendBufferSize", 1024 * 64);
    bootstrap.setOption("child.receiveBufferSize", 1024 * 64);

    // bootstrap.setOption("child.soLinger", 0);
}
 
Example 18
Source File: NetworkFailuresProxy.java    From flink with Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

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

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

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example 19
Source File: RpcServerBootstrap.java    From voyage with Apache License 2.0 4 votes vote down vote up
private void initHttpBootstrap(int myport) {
	logger.info("initHttpBootstrap...........");
	final ServerConfig serverConfig = new ServerConfig(myport);
	final ChannelGroup channelGroup = new DefaultChannelGroup(getClass().getName());
	bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
			//建议用ThreadPoolExecutor代替
			Executors.newCachedThreadPool(),
			Executors.newCachedThreadPool(), serverConfig.getThreadCnt()));
	//设置常见参数
	bootstrap.setOption("tcpNoDelay","true");//禁用nagle算法
	bootstrap.setOption("reuseAddress", "true");
	bootstrap.setOption("SO_RCVBUF",1024*128);
	bootstrap.setOption("SO_SNDBUF",1024*128);
	timer = new HashedWheelTimer();
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			int readTimeout = serverConfig.getReadTimeout();
			if (readTimeout > 0) {
				pipeline.addLast("timeout", new ReadTimeoutHandler(timer, readTimeout, TimeUnit.MILLISECONDS));
			}
			pipeline.addLast("decoder", new RpcRequestDecode());
			pipeline.addLast("encoder", new RpcResponseEncode());
			pipeline.addLast("handler", new NettyRpcServerHandler(channelGroup));
			return pipeline;
		}
	});
	
	int port = serverConfig.getPort();
	if (!checkPortConfig(port)) {
		throw new IllegalStateException("port: " + port + " already in use!");
	}

	Channel channel = bootstrap.bind(new InetSocketAddress(port));
	channelGroup.add(channel);
	logger.info("voyage server started");

	waitForShutdownCommand();
	ChannelGroupFuture future = channelGroup.close();
	future.awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	timer.stop();
	timer = null;

	logger.info("voyage server stoped");

}
 
Example 20
Source File: MockEndpoint.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
public void run() {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    b.setPipelineFactory(new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline p = pipeline();

            p.addLast("idle-detection", IDLE_STATE_HANDLER);
            p.addLast("http-decoder", new HttpRequestDecoder());
            p.addLast("http-encoder", new HttpResponseEncoder());
            p.addLast("keep-alive", KEEP_ALIVE_HANDLER);
            p.addLast("responder", new ChannelUpstreamHandler() {

                @Override
                public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
                    if (e instanceof MessageEvent) {
                        final MessageEvent me = (MessageEvent) e;
                        LOG.debug("received: {}", me.getMessage().getClass().getSimpleName());

                        Map<String, List<String>> params = new HashMap<>();

                        StringBuffer buf = new StringBuffer();
                        buf.setLength(0);
                        buf.append("HI");

                        if (me.getMessage() instanceof HttpRequest) {
                            final HttpRequest request = (HttpRequest) me.getMessage();

                            LOG.debug("request: {}", request);

                            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
                            params = queryStringDecoder.getParameters();

                            if (!request.isChunked()) {
                                writeOutput(e.getChannel(), buf, params.containsKey("chunked"));
                            }
                        } else if (me.getMessage() instanceof HttpChunk) {
                            final HttpChunk chunk = (HttpChunk) me.getMessage();
                            if (chunk.isLast()) {
                                writeOutput(e.getChannel(), buf, params.containsKey("chunked"));
                            }
                        }
                    }
                }
            });

            return p;
        }

    });

    b.setOption("child.tcpNoDelay", true);
    //b.setOption("receiveBufferSizePredictorFactory", new AdaptiveReceiveBufferSizePredictorFactory(1024, 8192, 131072));
    b.bind(new InetSocketAddress(PORT));

    LOG.info("server bound to port {}", PORT);
}