List of usage examples for io.netty.bootstrap ServerBootstrap childOption
public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value)
From source file:net.tomp2p.connection2.ChannelServer.java
License:Apache License
/** * Start to listen on a TCP port.//ww w. ja v a 2 s . co m * * @param listenAddresses * The address to listen to * @param config * Can create handlers to be attached to this port * @return True if startup was successful */ boolean startupTCP(final InetSocketAddress listenAddresses, final ChannelServerConficuration config) { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { for (Map.Entry<String, ChannelHandler> entry : handlers(true).entrySet()) { ch.pipeline().addLast(entry.getKey(), entry.getValue()); } } }); // b.option(ChannelOption.SO_BACKLOG, BACKLOG); b.childOption(ChannelOption.SO_LINGER, 0); b.childOption(ChannelOption.TCP_NODELAY, true); ChannelFuture future = b.bind(listenAddresses); channelTCP = future.channel(); return handleFuture(future); }
From source file:org.apache.activemq.artemis.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java
License:Apache License
private void startWebServer(int port) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//from w w w. j a v a 2 s . c o m protected void initChannel(SocketChannel ch) throws Exception { // create a HTTP server ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() { // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting. @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; for (Map.Entry<String, String> entry : request.headers()) { System.out.println(entry); } String upgrade = request.headers().get(UPGRADE); String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); response.headers().set(UPGRADE, upgrade); response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); ctx.writeAndFlush(response); // when the handshake is successful, the HTTP handlers are removed ctx.pipeline().remove("decoder"); ctx.pipeline().remove("encoder"); ctx.pipeline().remove(this); System.out.println("HTTP handshake sent, transferring channel"); // transfer the control of the channel to the Netty Acceptor NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService() .getAcceptor(acceptorName); acceptor.transfer(ctx.channel()); // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. } } }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }); b.bind(port).sync(); }
From source file:org.apache.activemq.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java
License:Apache License
private void startWebServer(int port) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/* w ww . j a v a2 s . c om*/ protected void initChannel(SocketChannel ch) throws Exception { // create a HTTP server ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() { // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ remoting. @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; for (Map.Entry<String, String> entry : request.headers()) { System.out.println(entry); } String upgrade = request.headers().get(UPGRADE); String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); response.headers().set(UPGRADE, upgrade); response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); ctx.writeAndFlush(response); // when the handshake is successful, the HTTP handlers are removed ctx.pipeline().remove("decoder"); ctx.pipeline().remove("encoder"); ctx.pipeline().remove(this); System.out.println("HTTP handshake sent, transferring channel"); // transfer the control of the channel to the Netty Acceptor NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService() .getAcceptor(acceptorName); acceptor.transfer(ctx.channel()); // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. } } }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }); b.bind(port).sync(); }
From source file:org.apache.bookkeeper.proto.BookieNettyServer.java
License:Apache License
private void listenOn(InetSocketAddress address, BookieSocketAddress bookieAddress) throws InterruptedException { if (!conf.isDisableServerSocketBind()) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.childOption(ChannelOption.ALLOCATOR, allocator); bootstrap.group(eventLoopGroup, eventLoopGroup); bootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay()); bootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger()); bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax())); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark())); if (eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.channel(EpollServerSocketChannel.class); } else {//from w w w .java2 s . c o m bootstrap.channel(NioServerSocketChannel.class); } bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { synchronized (suspensionLock) { while (suspended) { suspensionLock.wait(); } } BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler(); ChannelPipeline pipeline = ch.pipeline(); // For ByteBufList, skip the usual LengthFieldPrepender and have the encoder itself to add it pipeline.addLast("bytebufList", ByteBufList.ENCODER_WITH_SIZE); pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("lengthprepender", new LengthFieldPrepender(4)); pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry)); pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler( contextHandler.getConnectionPeer(), authProviderFactory)); ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler(); pipeline.addLast("bookieRequestHandler", requestHandler); pipeline.addLast("contextHandler", contextHandler); } }); // Bind and start to accept incoming connections Channel listen = bootstrap.bind(address.getAddress(), address.getPort()).sync().channel(); if (listen.localAddress() instanceof InetSocketAddress) { if (conf.getBookiePort() == 0) { conf.setBookiePort(((InetSocketAddress) listen.localAddress()).getPort()); } } } if (conf.isEnableLocalTransport()) { ServerBootstrap jvmBootstrap = new ServerBootstrap(); jvmBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)); jvmBootstrap.group(jvmEventLoopGroup, jvmEventLoopGroup); jvmBootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay()); jvmBootstrap.childOption(ChannelOption.SO_KEEPALIVE, conf.getServerSockKeepalive()); jvmBootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger()); jvmBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax())); jvmBootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark())); if (jvmEventLoopGroup instanceof DefaultEventLoopGroup) { jvmBootstrap.channel(LocalServerChannel.class); } else if (jvmEventLoopGroup instanceof EpollEventLoopGroup) { jvmBootstrap.channel(EpollServerSocketChannel.class); } else { jvmBootstrap.channel(NioServerSocketChannel.class); } jvmBootstrap.childHandler(new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) throws Exception { synchronized (suspensionLock) { while (suspended) { suspensionLock.wait(); } } BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler(); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("lengthprepender", new LengthFieldPrepender(4)); pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry)); pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler( contextHandler.getConnectionPeer(), authProviderFactory)); ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler(); pipeline.addLast("bookieRequestHandler", requestHandler); pipeline.addLast("contextHandler", contextHandler); } }); // use the same address 'name', so clients can find local Bookie still discovering them using ZK jvmBootstrap.bind(bookieAddress.getLocalAddress()).sync(); LocalBookiesRegistry.registerLocalBookieAddress(bookieAddress); } }
From source file:org.apache.carbondata.core.dictionary.server.DictionaryServer.java
License:Apache License
/** * start dictionary server//from w w w .j ava 2s. com * * @param port * @throws Exception */ public void startServer(int port) { long start = System.currentTimeMillis(); dictionaryServerHandler = new DictionaryServerHandler(); boss = new NioEventLoopGroup(); worker = new NioEventLoopGroup(); // Configure the server. try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("DictionaryServerHandler", dictionaryServerHandler); } }); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); bootstrap.bind(port).sync(); LOGGER.info("Dictionary Server started, Time spent " + (System.currentTimeMillis() - start) + " Listening on port " + port); } catch (Exception e) { LOGGER.error(e, "Dictionary Server Start Failed"); throw new RuntimeException(e); } }
From source file:org.apache.carbondata.core.dictionary.server.NonSecureDictionaryServer.java
License:Apache License
/** * Binds dictionary server to an available port. * *//*from w ww . j a v a 2s .c o m*/ @Override public void bindToPort() { long start = System.currentTimeMillis(); // Configure the server. int i = 0; while (i < 10) { int newPort = port + i; try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("LengthDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 2, 0, 2)); pipeline.addLast("NonSecureDictionaryServerHandler", nonSecureDictionaryServerHandler); } }); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); String hostToBind = findLocalIpAddress(LOGGER); //iteratively listening to newports InetSocketAddress address = hostToBind == null ? new InetSocketAddress(newPort) : new InetSocketAddress(hostToBind, newPort); bootstrap.bind(address).sync(); LOGGER.info("Dictionary Server started, Time spent " + (System.currentTimeMillis() - start) + " Listening on port " + newPort); this.port = newPort; this.host = hostToBind; break; } catch (Exception e) { LOGGER.error("Dictionary Server Failed to bind to port:" + newPort, e); if (i == 9) { throw new RuntimeException("Dictionary Server Could not bind to any port"); } } i++; } }
From source file:org.apache.dubbo.qos.server.Server.java
License:Apache License
/** * start server, bind port//w w w . ja v a2 s . c om */ public void start() throws Throwable { if (!started.compareAndSet(false, true)) { return; } boss = new NioEventLoopGroup(1, new DefaultThreadFactory("qos-boss", true)); worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true)); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true); serverBootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new QosProcessHandler(welcome, acceptForeignIp)); } }); try { serverBootstrap.bind(port).sync(); logger.info("qos-server bind localhost:" + port); } catch (Throwable throwable) { logger.error("qos-server can not bind localhost:" + port, throwable); throw throwable; } }
From source file:org.apache.hadoop.hbase.ipc.NettyRpcServer.java
License:Apache License
public NettyRpcServer(final Server server, final String name, final List<BlockingServiceAndInterface> services, final InetSocketAddress bindAddress, Configuration conf, RpcScheduler scheduler) throws IOException { super(server, name, services, bindAddress, conf, scheduler); this.bindAddress = bindAddress; boolean useEpoll = useEpoll(conf); int workerCount = conf.getInt("hbase.netty.rpc.server.worker.count", Runtime.getRuntime().availableProcessors() / 4); EventLoopGroup bossGroup = null;/*from w w w . ja v a 2s . c om*/ EventLoopGroup workerGroup = null; if (useEpoll) { bossGroup = new EpollEventLoopGroup(1); workerGroup = new EpollEventLoopGroup(workerCount); } else { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(workerCount); } ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup); if (useEpoll) { bootstrap.channel(EpollServerSocketChannel.class); } else { bootstrap.channel(NioServerSocketChannel.class); } bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, tcpKeepAlive); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.childHandler(new Initializer(maxRequestSize)); try { serverChannel = bootstrap.bind(this.bindAddress).sync().channel(); LOG.info("NettyRpcServer bind to address=" + serverChannel.localAddress() + ", hbase.netty.rpc.server.worker.count=" + workerCount + ", useEpoll=" + useEpoll); allChannels.add(serverChannel); } catch (InterruptedException e) { throw new InterruptedIOException(e.getMessage()); } initReconfigurable(conf); this.scheduler.init(new RpcSchedulerContext(this)); }
From source file:org.apache.pulsar.common.util.netty.EventLoopUtil.java
License:Apache License
public static void enableTriggeredMode(ServerBootstrap bootstrap) { if (Epoll.isAvailable()) { bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); }/*from w ww . ja va 2s . c o m*/ }
From source file:org.apache.pulsar.proxy.server.ProxyService.java
License:Apache License
public void start() throws Exception { if (!isBlank(proxyConfig.getZookeeperServers()) && !isBlank(proxyConfig.getConfigurationStoreServers())) { discoveryProvider = new BrokerDiscoveryProvider(this.proxyConfig, getZooKeeperClientFactory()); this.configurationCacheService = new ConfigurationCacheService(discoveryProvider.globalZkCache); authorizationService = new AuthorizationService(PulsarConfigurationLoader.convertFrom(proxyConfig), configurationCacheService); }//from w w w.j a v a2 s . c o m ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.group(acceptorGroup, workerGroup); bootstrap.childOption(ChannelOption.TCP_NODELAY, true); bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024)); bootstrap.channel(EventLoopUtil.getServerSocketChannelClass(workerGroup)); EventLoopUtil.enableTriggeredMode(bootstrap); bootstrap.childHandler(new ServiceChannelInitializer(this, proxyConfig, false)); // Bind and start to accept incoming connections. if (proxyConfig.getServicePort().isPresent()) { try { bootstrap.bind(proxyConfig.getServicePort().get()).sync(); LOG.info("Started Pulsar Proxy at {}", serviceUrl); } catch (Exception e) { throw new IOException("Failed to bind Pulsar Proxy on port " + proxyConfig.getServicePort().get(), e); } } LOG.info("Started Pulsar Proxy at {}", serviceUrl); if (proxyConfig.getServicePortTls().isPresent()) { ServerBootstrap tlsBootstrap = bootstrap.clone(); tlsBootstrap.childHandler(new ServiceChannelInitializer(this, proxyConfig, true)); tlsBootstrap.bind(proxyConfig.getServicePortTls().get()).sync(); LOG.info("Started Pulsar TLS Proxy on port {}", proxyConfig.getServicePortTls().get()); } }