Example usage for io.netty.bootstrap ServerBootstrap ServerBootstrap

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

Introduction

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

Prototype

public ServerBootstrap() 

Source Link

Usage

From source file:com.dwarf.netty.guide.factorial.FactorialServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  www.jav a  2 s. com*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new FactorialServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from ww  w. j  a v  a 2  s .co m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpSnoopServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.dwarf.netty.guide.securechat.SecureChatServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w ww. j  av  a2  s .c  o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SecureChatServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.dwarf.netty.guide.worldclock.WorldClockServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  www .j ava2 s .c  o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new WorldClockServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.ebay.jetstream.http.netty.server.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler/*w  w w .  j  av a2 s.  c o m*/
 * @throws Exception
 */
public void bind(final HttpRequestHandler httpReqHandler, final HttpServerStatisticsHandler statisticsHandler)
        throws Exception {
    m_bossGroup = new NioEventLoopGroup(1, new NameableThreadFactory("NettyHttpServerAcceptor"));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyHttpServerWorker"));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        ch.pipeline().addLast("stats", statisticsHandler);
                        ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                        ch.pipeline().addLast("deflater", new HttpContentCompressor(1));
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(m_maxContentLength));
                        if (m_maxKeepAliveRequests > 0 || m_maxKeepAliveTimeout > 0) {
                            ch.pipeline().addLast("keepAliveHandler",
                                    new KeepAliveHandler(m_maxKeepAliveRequests, m_maxKeepAliveTimeout));
                        }
                        ch.pipeline().addLast("handler", httpReqHandler);

                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, false);

        if (m_config.getRvcBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, (int) m_config.getRvcBufSz());
        }

        if (m_config.getSendBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, (int) m_config.getSendBufSz());
        }

    } catch (Exception t) {
        throw t;
    }

    m_acceptorSocket = new InetSocketAddress(m_ipAddress, m_tcpPort);
    m_serverbootstrap.bind(m_acceptorSocket).sync();

    if (!m_ipAddress.isLoopbackAddress() && !m_ipAddress.isAnyLocalAddress()) {
        // Add lookback if not bind
        m_localAcceptorSocket = new InetSocketAddress("127.0.0.1", m_tcpPort);
        m_serverbootstrap.bind(m_localAcceptorSocket).sync();
    }
}

From source file:com.ebay.jetstream.messaging.transport.netty.eventconsumer.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler//ww  w.  ja v a  2 s . c om
 * @throws Exception
 */
public void bind(EventProducerSessionHandler rxSessionHandler) throws Exception {

    m_rxSessionHandler = rxSessionHandler;
    m_bossGroup = new NioEventLoopGroup(1,
            new NameableThreadFactory("NettyAcceptor-" + m_tc.getTransportName()));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyReceiver-" + m_tc.getTransportName()));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addFirst("msghandler", m_rxSessionHandler);

                        StreamMessageDecoder decoder = new StreamMessageDecoder(
                                ClassResolvers.weakCachingConcurrentResolver(null));
                        ch.pipeline().addBefore("msghandler", "msgdecoder", decoder);
                        ch.pipeline().addBefore("msgdecoder", "kryoEcnoder", new KryoObjectEncoder());
                        ch.pipeline().addBefore("kryoEcnoder", "msgencoder", new NettyObjectEncoder());

                        if (m_enableCompression) {

                            ch.pipeline().addBefore("msgencoder", "decompressor",
                                    new MessageDecompressionHandler(false, 250000));

                            ch.pipeline().addBefore("decompressor", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        } else
                            ch.pipeline().addBefore("msgencoder", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));

                    }
                }).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.SO_KEEPALIVE, isTcpKeepAlive());

        if (m_tc.getReceivebuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, m_tc.getReceivebuffersize());
        }

        if (m_tc.getSendbuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, m_tc.getSendbuffersize());
        }

    } catch (Exception t) {
        throw t;
    }

    // we are given a port from DNS. We will check if it is taken. If it is
    // we will increment the port # by 10 and keep trying 10 times.
    // adding this feature so that we can operate the cluster on a single
    // node. Very useful for debugging and also for demos.

    int retryCount = 20;
    int port = m_tcpPort;

    while (retryCount-- > 0) {
        if (isPortAvailable(port))
            break;
        port += 1;

    }

    if (retryCount == 0)
        return; // we did not find a port to bind

    m_tcpPort = port;

    LOGGER.info("Acceptor bound to port" + m_tcpPort);

}

From source file:com.eightkdata.mongowp.mongoserver.MongoServer.java

License:Open Source License

public void run() {
    // TODO: provide custom ThreadFactories to the EventLoopGroup to name threads correctly?
    connectionGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {/*from w ww .jav a2s .c  o m*/
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(connectionGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        buildChildHandlerPipeline(socketChannel.pipeline());
                    }
                })
        // TODO: set TCP channel options?
        ;

        ChannelFuture channelFuture = bootstrap.bind(port).awaitUninterruptibly();

        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException interruptedException) {
            LOGGER.error("Error", interruptedException);
            // TODO: perform proper shutdown
        } catch (Throwable throwable) {
            LOGGER.error("Error", throwable);
            // TODO: perform proper shutdown
        }
    } finally {
        workerGroup.shutdownGracefully();
        connectionGroup.shutdownGracefully();
    }
}

From source file:com.eightkdata.mongowp.server.wp.NettyMongoServer.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    LOGGER.info("Listening MongoDB requests on port " + port);

    connectionGroup = new NioEventLoopGroup(0,
            new ThreadFactoryBuilder().setNameFormat("netty-connection-%d").build());
    workerGroup = new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("netty-worker-%d").build());

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(connectionGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//w w  w.j  a v a2s .com
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    buildChildHandlerPipeline(socketChannel.pipeline());
                }
            }) // TODO: set TCP channel options?
    ;

    ChannelFuture channelFuture = bootstrap.bind(port).awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        workerGroup.shutdownGracefully();
        connectionGroup.shutdownGracefully();
    }
}

From source file:com.example.discard.DiscardServerMain.java

License:Apache License

public void run() throws Exception {
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();//1
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    try (AutoCloseable ignore = new ShutDownGracefully(bossGroup, workerGroup)) {
        final ServerBootstrap bootstrap = new ServerBootstrap();//2
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)//3
                .childHandler(new ChannelInitializer<SocketChannel>() {//4
                    @Override/*from w  w w .j  a  v a2 s. c o  m*/
                    protected void initChannel(final SocketChannel ch) {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128)//5
                .childOption(ChannelOption.SO_KEEPALIVE, true); //6
        final ChannelFuture channelFuture = bootstrap.bind(port).sync();//7
        channelFuture.channel().closeFuture().sync();
    }
}

From source file:com.example.grpc.server.PrometheusServer.java

License:Apache License

public void start() {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//  w w  w.java  2  s  .c  o m
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("decoder", new HttpRequestDecoder());
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("prometheus", new SimpleChannelInboundHandler<Object>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o)
                                throws Exception {
                            if (!(o instanceof HttpRequest)) {
                                return;
                            }

                            HttpRequest request = (HttpRequest) o;

                            if (!"/metrics".equals(request.uri())) {
                                final FullHttpResponse response = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
                                channelHandlerContext.writeAndFlush(response)
                                        .addListener(ChannelFutureListener.CLOSE);
                                return;
                            }

                            if (!HttpMethod.GET.equals(request.method())) {
                                final FullHttpResponse response = new DefaultFullHttpResponse(
                                        HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_ACCEPTABLE);
                                channelHandlerContext.writeAndFlush(response)
                                        .addListener(ChannelFutureListener.CLOSE);
                                return;
                            }

                            ByteBuf buf = Unpooled.buffer();
                            ByteBufOutputStream os = new ByteBufOutputStream(buf);
                            OutputStreamWriter writer = new OutputStreamWriter(os);
                            TextFormat.write004(writer, registry.metricFamilySamples());
                            writer.close();
                            os.close();

                            final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                                    HttpResponseStatus.OK, buf);
                            response.headers().set(HttpHeaderNames.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004);
                            channelHandlerContext.writeAndFlush(response)
                                    .addListener(ChannelFutureListener.CLOSE);
                        }
                    });

                }
            });

    try {
        this.channel = bootstrap.bind(this.port).sync().channel();
    } catch (InterruptedException e) {
        // do nothing
    }
}