Example usage for io.netty.handler.ssl SslContextBuilder forServer

List of usage examples for io.netty.handler.ssl SslContextBuilder forServer

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder forServer.

Prototype

boolean forServer

To view the source code for io.netty.handler.ssl SslContextBuilder forServer.

Click Source Link

Usage

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

SSLSocket(SSLAcceptor acceptor, SocketChannel socket, InputStream publicKey, InputStream privateKey,
        String passwd) throws SSLException {
    super(acceptor, socket);
    SslContext ctx = (passwd != null ? SslContextBuilder.forServer(publicKey, privateKey, passwd)
            : SslContextBuilder.forServer(publicKey, privateKey)).build();
    socket.pipeline().addBefore("readManager", "ssl", ctx.newHandler(socket.alloc()));
}

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

SSLSocket(SSLAcceptor acceptor, SocketChannel socket, SSLAcceptorConfigurator configurator)
        throws SSLException {
    super(acceptor, socket);
    SslContextBuilder builder = SslContextBuilder.forServer(configurator.getFactory());
    configurator.configure(builder);/*from  w  ww  .j a  v a 2  s.c om*/
    SslHandler handler = builder.build().newHandler(socket.alloc());
    SSLParameters p = handler.engine().getSSLParameters();
    SSLParameters np = configurator.changeParameters(p);
    if (np != null)
        handler.engine().setSSLParameters(np);
    socket.pipeline().addBefore("readManager", "ssl", handler);
}

From source file:me.netty.http.HttpServer.java

License:Apache License

public void start() throws Exception {
    //?/*from  ww  w  .ja v a2  s.  co m*/
    serverContext.initContext();

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the http2Orhttp.

    //CPU??workwork?
    // ?????
    int threads = Runtime.getRuntime().availableProcessors() * 2;

    EventLoopGroup bossGroup = new NioEventLoopGroup(threads);
    EventLoopGroup workerGroup = new NioEventLoopGroup(threads);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new Http2ServerInitializer(sslCtx));

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

        logger.info("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "http")
                + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync().addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                logger.info("service has shutdown");
            }
        });
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

From source file:net.anyflow.menton.http.WebServerChannelInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if ("true".equalsIgnoreCase(Settings.SELF.getProperty("menton.logging.writelogOfNettyLogger"))) {
        ch.pipeline().addLast("log", new LoggingHandler("menton/server", LogLevel.DEBUG));
    }//from   ww  w.  j  av a 2s.c o m

    if (useSsl) {
        SslContext sslCtx = SslContextBuilder
                .forServer(Settings.SELF.certChainFile(), Settings.SELF.privateKeyFile()).build();

        logger.debug("SSL Provider : {}", SslContext.defaultServerProvider());

        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
    }

    ch.pipeline().addLast(HttpServerCodec.class.getName(), new HttpServerCodec());
    ch.pipeline().addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(1048576));
    ch.pipeline().addLast(HttpContentCompressor.class.getName(), new HttpContentCompressor());
    ch.pipeline().addLast(HttpRequestRouter.class.getName(), new HttpRequestRouter());

    if (websocketFrameHandlerClass != null) {
        WebsocketFrameHandler wsfh = websocketFrameHandlerClass.newInstance();

        ch.pipeline().addLast(WebSocketServerProtocolHandler.class.getName(),
                new WebSocketServerProtocolHandler(wsfh.websocketPath(), wsfh.subprotocols(),
                        wsfh.allowExtensions(), wsfh.maxFrameSize()));

        ch.pipeline().addLast(wsfh);
    }
}

From source file:netty.echo.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from   ww  w  .  j  ava 2 s  .  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.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        //?handler
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        //bindNioServerSocketChannelServerSocket
        ChannelFuture f = b.bind(PORT).sync();
        //ChannelFuture.result, ?resultSignal SUCCESS = Signal.valueOf(DefaultPromise.class, "SUCCESS");,
        // sync()?,?

        // Wait until the server socket is closed.
        //closeFuture.result?future?
        //??,?,?
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:netty.server.NettyHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from w w w.  j ava 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 NettyHelloWorldInitializer(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:netty.WebSocketServer.java

License:Apache License

public void startServer(GameServer gameServer, ObjectMapper objectMapper) {
    // Configure SSL.

    SslContext sslCtx;// w w  w. j av  a2  s  .com
    if (SSL) {
        try {
            SelfSignedCertificate ssc = null;

            ssc = new SelfSignedCertificate();

            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } catch (CertificateException | SSLException e) {
            logger.error("failed to set up ssl ", e);
            sslCtx = null;
        }

    } 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, gameServer, objectMapper));

        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();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:nettyFileServer.FileServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  w w  w  . j av 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();
    System.out.println("Running the server");
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                //.handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(8192),
                                new StringDecoder(CharsetUtil.UTF_8), new ChunkedWriteHandler(),
                                new FileServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:nettyTest.httpSsl.oneWay.HttpsHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w w  w .  java2 s  . c  om*/
        File certificate = new File(
                HttpsHelloWorldServer.class.getClassLoader().getResource("nettyca/server.crt").getFile());
        File privateKey = new File(
                HttpsHelloWorldServer.class.getClassLoader().getResource("nettyca/server.pem").getFile());
        sslCtx = SslContextBuilder.forServer(certificate, privateKey).build();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    } 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 HttpsHelloWorldServerInitializer(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:network.thunder.core.communication.nio.P2PServer.java

License:Apache License

public void startServer(int port, ArrayList<Node> connectedNodes) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {// w  ww.j  a v  a 2 s .  co  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInit(context, true));

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