Example usage for io.netty.bootstrap ServerBootstrap childHandler

List of usage examples for io.netty.bootstrap ServerBootstrap childHandler

Introduction

In this page you can find the example usage for io.netty.bootstrap ServerBootstrap childHandler.

Prototype

ChannelHandler childHandler

To view the source code for io.netty.bootstrap ServerBootstrap childHandler.

Click Source Link

Usage

From source file:net.hasor.rsf.console.RsfConsoleModule.java

License:Apache License

@Override
public void onStart(AppContext appContext) throws Throwable {
    RsfContext rsfContext = appContext.getInstance(RsfContext.class);
    if (rsfContext == null) {
        logger.error("rsfConsole -> RsfContext is null.");
        return;//from   www .  j  a  va  2 s.  c o  m
    }
    //1.???
    this.workerGroup = new NioEventLoopGroup(1,
            new NameThreadFactory("RSF-Console", appContext.getClassLoader()));
    this.telnetHandler = new TelnetHandler(rsfContext);
    int consolePort = rsfContext.getSettings().getConsolePort();
    String consoleAddress = rsfContext.getSettings().getBindAddress();
    String formUnit = rsfContext.getSettings().getUnitName();
    try {
        this.bindAddress = new InterAddress(consoleAddress, consolePort, formUnit);
    } catch (Throwable e) {
        throw new UnknownHostException(e.getMessage());
    }
    logger.info("rsfConsole -> starting... at {}", this.bindAddress);
    //
    //2.?Telnet
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(workerGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                pipeline.addLast(stringDecoder);
                pipeline.addLast(stringEncoder);
                pipeline.addLast(telnetHandler);
            }
        });
        b.bind(this.bindAddress.getHost(), this.bindAddress.getPort()).sync().await();
    } catch (Throwable e) {
        logger.error("rsfConsole -> start failed, " + e.getMessage(), e);
        this.shutdown();
    }
    logger.info("rsfConsole -> - bindSocket at {}", this.bindAddress);
    //
    //3.shutdown??shutdown??Telnet
    Hasor.addShutdownListener(rsfContext.getEnvironment(), new EventListener<AppContext>() {
        @Override
        public void onEvent(String event, AppContext eventData) throws Throwable {
            shutdown();
        }
    });
}

From source file:net.hasor.rsf.rpc.net.Connector.java

License:Apache License

/**
 * ??// w w  w. j av  a2 s .c o m
 * @param listenLoopGroup ?
 */
public void startListener(NioEventLoopGroup listenLoopGroup) {
    //
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(listenLoopGroup, this.workLoopGroup);
    boot.channel(NioServerSocketChannel.class);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelHandler[] handlerArrays = channelHandler();
            ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
            handlers.addAll(Arrays.asList(handlerArrays)); // ??
            handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF
            //
            ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
        }
    });
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture future = configBoot(boot).bind(this.bindAddress.toSocketAddress());
    //
    final BasicFuture<RsfChannel> result = new BasicFuture<RsfChannel>();
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                future.channel().close();
                result.failed(future.cause());
            } else {
                Channel channel = future.channel();
                result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Listener));
            }
        }
    });
    try {
        this.localListener = result.get();
        logger.info("rsf Server started at {}", this.bindAddress);
    } catch (Exception e) {
        logger.error("rsf start listener error: " + e.getMessage(), e);
        throw new RsfException(ProtocolStatus.NetworkError,
                this.bindAddress.toString() + " -> " + e.getMessage());
    }
    //
}

From source file:net.mcsproject.master.network.DaemonServer.java

License:Open Source License

public DaemonServer(int port) {
    this.thread = new Thread(() -> {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {/*from  ww w .j  ava2 s.  c om*/
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new PacketDecoder()).addLast(new PacketEncoder())
                            .addLast(new PacketMessageHandler());
                }
            });
            bootstrap.option(ChannelOption.SO_BACKLOG, 50);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("Server started!");
            future.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    });

    thread.setName("DaemonServer Thread");
    thread.start();
}

From source file:net.tomp2p.connection.ChannelServer.java

License:Apache License

/**
 * Start to listen on a TCP port.//from www  . ja v a  2s.c  om
 * 
 * @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 ChannelServerConfiguration 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 {
            ch.config().setAllocator(channelServerConfiguration.byteBufAllocator());
            // b.option(ChannelOption.SO_BACKLOG, BACKLOG);
            bestEffortOptions(ch, ChannelOption.SO_LINGER, 0);
            bestEffortOptions(ch, ChannelOption.TCP_NODELAY, true);
            for (Map.Entry<String, Pair<EventExecutorGroup, ChannelHandler>> entry : handlers(true)
                    .entrySet()) {
                if (!entry.getValue().isEmpty()) {
                    ch.pipeline().addLast(entry.getValue().element0(), entry.getKey(),
                            entry.getValue().element1());
                } else if (entry.getValue().element1() != null) {
                    ch.pipeline().addLast(entry.getKey(), entry.getValue().element1());
                }
            }
        }
    });
    ChannelFuture future = b.bind(listenAddresses);
    channelsTCP.put(listenAddresses.getAddress(), future.channel());
    return handleFuture(future);
}

From source file:net.tomp2p.connection2.ChannelServer.java

License:Apache License

/**
 * Start to listen on a TCP port.//from   w ww.j  a va2s . c  om
 * 
 * @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.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 {/*  w w w.j  av a 2  s . c om*/
            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/* w w  w .  j  a va  2s  . c o m*/
 *
 * @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.
 *
 */// ww w . j  a va2  s .  com
@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.cassandra.transport.Server.java

License:Apache License

private void run() {
    // Configure the server.
    eventExecutorGroup = new RequestThreadPoolExecutor();

    boolean hasEpoll = enableEpoll ? Epoll.isAvailable() : false;
    if (hasEpoll) {
        workerGroup = new EpollEventLoopGroup();
        logger.info("Netty using native Epoll event loop");
    } else {/* ww  w .  j ava 2 s . com*/
        workerGroup = new NioEventLoopGroup();
        logger.info("Netty using Java NIO event loop");
    }

    ServerBootstrap bootstrap = new ServerBootstrap().group(workerGroup)
            .channel(hasEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_LINGER, 0)
            .childOption(ChannelOption.SO_KEEPALIVE, DatabaseDescriptor.getRpcKeepAlive())
            .childOption(ChannelOption.ALLOCATOR, CBUtil.allocator)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

    final EncryptionOptions.ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions();
    if (clientEnc.enabled) {
        logger.info("Enabling encrypted CQL connections between client and server");
        bootstrap.childHandler(new SecureInitializer(this, clientEnc));
    } else {
        bootstrap.childHandler(new Initializer(this));
    }

    // Bind and start to accept incoming connections.
    logger.info("Using Netty Version: {}", Version.identify().entrySet());
    logger.info("Starting listening for CQL clients on {}...", socket);

    ChannelFuture bindFuture = bootstrap.bind(socket);
    if (!bindFuture.awaitUninterruptibly().isSuccess())
        throw new IllegalStateException(String.format("Failed to bind port %d on %s.", socket.getPort(),
                socket.getAddress().getHostAddress()));

    connectionTracker.allChannels.add(bindFuture.channel());
    isRunning.set(true);

    StorageService.instance.setRpcReady(true);
}

From source file:org.apache.cxf.transport.http.netty.server.NettyHttpServerEngine.java

License:Apache License

protected Channel startServer() {

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, true);

    // Set up the event pipeline factory.
    servletPipeline = new NettyHttpServletPipelineFactory(tlsServerParameters, sessionSupport,
            threadingParameters.getThreadPoolSize(), maxChunkContentSize, handlerMap, this);
    // Start the servletPipeline's timer
    servletPipeline.start();//  www  .  j a va 2s.c om
    bootstrap.childHandler(servletPipeline);
    InetSocketAddress address = null;
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {
        address = new InetSocketAddress(host, port);
    }
    // Bind and start to accept incoming connections.
    try {
        return bootstrap.bind(address).sync().channel();
    } catch (InterruptedException ex) {
        // do nothing here
        return null;
    }
}