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.topsec.bdc.platform.api.test.http.helloworld.HttpHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//  w  w  w . j  a  v  a 2s.  c  o m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpHelloWorldServerInitializer(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.topsec.bdc.platform.api.test.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.jav  a2s .  c  om
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } 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.topsec.bdc.platform.api.test.http.upload.HttpUploadServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  www .  j  a v a 2s  .  com*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(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.topsec.bdc.platform.api.test.http.websocketx.benchmarkserver.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  ww  w. ja  va  2s  .c o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketServerInitializer(sslCtx));

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

        System.out.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.topsec.bdc.platform.api.test.http.websocketx.server.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {// w w w .  j a v  a  2s  . co  m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } 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 WebSocketServerInitializer(sslCtx));

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

        System.out.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.trinity.engine.protocol.detail.TrinityConnectionManager.java

License:Apache License

/**
 * Default constructor for {@link TrinityConnectionManager}
 *///w  w w .  j  a v  a2 s. c  o  m
public TrinityConnectionManager() {
    this.mRegistry = new ConcurrentHashMap<>();
    this.mGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    this.mBossGroup = new NioEventLoopGroup();
    this.mWorkerGroup = new NioEventLoopGroup();
    this.mBootstrap = new ServerBootstrap();
    this.mUncaughtExceptionHandler = new AtomicReference<>(new DefaultUncaughtExceptionHandler());
}

From source file:com.turn.ttorrent.client.io.PeerServer.java

License:Apache License

/**
 * Create and start a new listening service for our torrents, reporting
 * with our peer ID on the given address.
 *
 * <p>/*w  w w  . ja va 2 s.  c om*/
 * This binds to the first available port in the client port range
 * PORT_RANGE_START to PORT_RANGE_END.
 * </p>
 */
public void start() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(environment.getEventService());
    bootstrap.channel(environment.getEventLoopType().getServerChannelType());
    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childHandler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new PeerServerHandshakeHandler(torrents));
        }
    });
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    // bootstrap.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    SocketAddress address = environment.getLocalPeerListenAddress();
    if (address != null) {
        future = bootstrap.bind(address).sync();
    } else {
        BIND: {
            Exception x = new IOException("No available port for the BitTorrent client!");
            for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) {
                try {
                    future = bootstrap.bind(i).sync();
                    break BIND;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    x = e;
                }
            }
            throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + ","
                    + PORT_RANGE_END + "]", x);
        }
    }
}

From source file:com.turo.pushy.apns.BenchmarkApnsServer.java

License:Open Source License

public BenchmarkApnsServer(final InputStream certificateChainInputStream,
        final InputStream privateKeyPkcs8InputStream, final NioEventLoopGroup eventLoopGroup)
        throws SSLException {
    final SslContext sslContext;
    {/*from  w  w w . jav  a2 s .c  om*/
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            if (OpenSsl.isAlpnSupported()) {
                sslProvider = SslProvider.OPENSSL;
            } else {
                sslProvider = SslProvider.JDK;
            }
        } else {
            sslProvider = SslProvider.JDK;
        }

        sslContext = SslContextBuilder.forServer(certificateChainInputStream, privateKeyPkcs8InputStream, null)
                .sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                ApplicationProtocolNames.HTTP_2))
                .build();
    }

    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(eventLoopGroup);

    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline()
                    .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

                        @Override
                        protected void configurePipeline(final ChannelHandlerContext context,
                                final String protocol) throws Exception {
                            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                                context.pipeline().addLast(
                                        new BenchmarkApnsServerHandler.BenchmarkApnsServerHandlerBuilder()
                                                .initialSettings(new Http2Settings()
                                                        .maxConcurrentStreams(MAX_CONCURRENT_STREAMS))
                                                .build());

                                BenchmarkApnsServer.this.allChannels.add(context.channel());
                            } else {
                                throw new IllegalStateException("Unexpected protocol: " + protocol);
                            }
                        }
                    });
        }
    });
}

From source file:com.turo.pushy.apns.MockApnsServer.java

License:Open Source License

protected MockApnsServer(final SslContext sslContext, final EventLoopGroup eventLoopGroup) {
    this.bootstrap = new ServerBootstrap();

    if (eventLoopGroup != null) {
        this.bootstrap.group(eventLoopGroup);
        this.shouldShutDownEventLoopGroup = false;
    } else {/*  ww  w  . j  a  v a 2 s.  co  m*/
        this.bootstrap.group(new NioEventLoopGroup(1));
        this.shouldShutDownEventLoopGroup = true;
    }

    this.bootstrap.channel(SocketChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group()));
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline()
                    .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

                        @Override
                        protected void configurePipeline(final ChannelHandlerContext context,
                                final String protocol) throws Exception {
                            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                                AbstractMockApnsServerHandler.AbstractMockApnsServerHandlerBuilder handlerBuilder;

                                try {
                                    final SSLSession sslSession = sslHandler.engine().getSession();

                                    // This will throw an exception if the peer hasn't authenticated (i.e. we're expecting
                                    // token authentication).
                                    final String principalName = sslSession.getPeerPrincipal().getName();

                                    final Pattern pattern = Pattern.compile(".*UID=([^,]+).*");
                                    final Matcher matcher = pattern.matcher(principalName);

                                    final String baseTopic;

                                    if (matcher.matches()) {
                                        baseTopic = matcher.group(1);
                                    } else {
                                        throw new IllegalArgumentException(
                                                "Client certificate does not specify a base topic.");
                                    }

                                    final TlsAuthenticationMockApnsServerHandler.TlsAuthenticationMockApnsServerHandlerBuilder tlsAuthenticationHandlerBuilder = new TlsAuthenticationMockApnsServerHandler.TlsAuthenticationMockApnsServerHandlerBuilder();

                                    tlsAuthenticationHandlerBuilder.baseTopic(baseTopic);

                                    handlerBuilder = tlsAuthenticationHandlerBuilder;
                                } catch (final SSLPeerUnverifiedException e) {
                                    // No need for alarm; this is an expected case
                                    final TokenAuthenticationMockApnsServerHandler.TokenAuthenticationMockApnsServerHandlerBuilder tokenAuthenticationHandlerBuilder = new TokenAuthenticationMockApnsServerHandler.TokenAuthenticationMockApnsServerHandlerBuilder();

                                    tokenAuthenticationHandlerBuilder.verificationKeysByKeyId(
                                            MockApnsServer.this.verificationKeysByKeyId);
                                    tokenAuthenticationHandlerBuilder.topicsByVerificationKey(
                                            MockApnsServer.this.topicsByVerificationKey);
                                    tokenAuthenticationHandlerBuilder.emulateExpiredFirstToken(
                                            MockApnsServer.this.emulateExpiredFirstToken);

                                    handlerBuilder = tokenAuthenticationHandlerBuilder;
                                }

                                context.pipeline().addLast(handlerBuilder
                                        .initialSettings(new Http2Settings().maxConcurrentStreams(8))
                                        .emulateInternalErrors(MockApnsServer.this.emulateInternalErrors)
                                        .deviceTokenExpirationsByTopic(
                                                MockApnsServer.this.deviceTokenExpirationsByTopic)
                                        .build());

                                MockApnsServer.this.allChannels.add(context.channel());
                            } else {
                                throw new IllegalStateException("Unexpected protocol: " + protocol);
                            }
                        }
                    });
        }
    });
}

From source file:com.turo.pushy.apns.server.BaseHttp2Server.java

License:Open Source License

BaseHttp2Server(final SslContext sslContext, final EventLoopGroup eventLoopGroup) {

    this.sslContext = sslContext;

    if (this.sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) this.sslContext).retain();
    }//from w ww .j a v a  2  s  .  c o  m

    this.bootstrap = new ServerBootstrap();

    if (eventLoopGroup != null) {
        this.bootstrap.group(eventLoopGroup);
        this.shouldShutDownEventLoopGroup = false;
    } else {
        this.bootstrap.group(new NioEventLoopGroup(1));
        this.shouldShutDownEventLoopGroup = true;
    }

    this.allChannels = new DefaultChannelGroup(this.bootstrap.config().group().next());

    this.bootstrap.channel(ServerChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group()));
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline().addLast(ConnectionNegotiationErrorHandler.INSTANCE);

            sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> handshakeFuture) throws Exception {
                    if (handshakeFuture.isSuccess()) {
                        BaseHttp2Server.this.addHandlersToPipeline(sslHandler.engine().getSession(),
                                channel.pipeline());
                        channel.pipeline().remove(ConnectionNegotiationErrorHandler.INSTANCE);

                        BaseHttp2Server.this.allChannels.add(channel);
                    } else {
                        log.debug("TLS handshake failed.", handshakeFuture.cause());
                    }
                }
            });
        }
    });
}