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:MyNettyServer.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  2  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())
                .childHandler(new ServerInitializer(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:nwses.java

License:Open Source License

/**
 * Main//from  www  .j  av a 2  s .  c o  m
 * @param args Optional command-line parameters for server port and tag
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    final int port;
    final String tag;

    boolean SSL = false;

    if (args.length == 0) {
        port = 80;
        tag = "server1";
    } else if (args.length == 1) {
        if (isValidPortNumber(args[0])) {
            port = Integer.parseInt(args[0]);
            tag = "server1";
        } else {
            return;
        }
    } else {
        if (isValidPortNumber(args[0])) {
            port = Integer.parseInt(args[0]);
            tag = args[1];
        } else {
            return;
        }

    }

    // If port 443 is specified to be used, use SSL.
    if (port == 443) {
        SSL = true;
        System.out.println("Websocket secure connection server initialized.");
    }

    final SslContext sslCtx;
    if (SSL) {
        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.TRACE))
                .childHandler(new WebSocketServerInitializer(sslCtx, tag));

        System.out.println("Server: " + tag + " started at port: " + port + " \n");

        Channel chnl = b.bind(port).sync().channel();
        chnl.closeFuture().sync();

    } catch (Exception e) { //Catch exceptions e.g. trying to open second server on same port
        System.err.println("Caught exception: " + e.getMessage());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        System.out.println("Server closed..");
    }
}

From source file:HttpSnoopServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    SslContext sslCtx = null;/*from   www  .ja va 2 s . c o  m*/

    try {
        File certChainFile = new File("/Users/hyecheon/netty.cst");
        File keyFile = new File("/Users/hyecheon/privatekey.pem");
        keyFile.exists();
        sslCtx = SslContext.newServerContext(certChainFile, keyFile, "HELLO");
    } catch (SSLException e) {
        e.printStackTrace();
        System.out.println("Can not create SSL context! \n Server will be stop!");
    }

    // 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();

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

From source file:WorldClockServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w  ww  . j  a va2s .co  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WorldClockServerInitializer());

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

From source file:NettyHttpListner.java

License:Apache License

public void start() {

    System.out.println("Starting the server...");
    System.out.println("Starting Inbound Http Listner on Port " + this.port);

    // Configure SSL.
    SslContext sslCtx = null;//w  w w .j  av  a  2 s  .  c  om
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SSLException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize);
    //        bossGroup = new NioEventLoopGroup(bossGroupSize);
    //        workerGroup = new NioEventLoopGroup(workerGroupSize);

    try {
        ServerBootstrap b = new ServerBootstrap();

        //            b.commonEventLoopGroup(bossGroup, workerGroup)
        b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                        new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx))
                .childOption(ChannelOption.AUTO_READ, false);

        b.option(ChannelOption.TCP_NODELAY, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);

        b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_SNDBUF, 1048576);

        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        Channel ch = null;
        try {
            ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("Inbound Listner Started");
        } catch (InterruptedException e) {
            System.out.println("Exception caught");
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:HttpUploadServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from w ww.  j  a  va 2 s  .c  o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpUploadServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        System.out.println("HTTP Upload Server at port " + port + '.');
        System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

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

From source file:NettyServer.java

License:Open Source License

void start() throws Exception {
    parentGroup = new NioEventLoopGroup(1);
    childGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap().group(parentGroup, childGroup)
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from ww  w.  j  a  v a 2s. co  m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();

                    pipeline.addLast("lineFrame", new LineBasedFrameDecoder(256));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("encoder", new StringEncoder());

                    pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            Channel channel = ctx.channel();
                            channelActiveHandler.accept(channel);
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            messageConsumer.accept(msg);
                        }
                    });
                }
            });
    channel = bootstrap.bind(port).channel();
    System.out.println("NettyServer started");
}

From source file:HttpRouterServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    Router<String> router = new Router<String>().GET(PUBLIC_DIR + ":id", "public").GET("/", "index")
            .GET(PUBLIC_DIR, "index")
            //            .GET("/image", "base64")
            //            .GET("/img", "image")
            //            .GET("/",             "Index page")
            //            .GET("/articles/:id", "Article show page")
            .notFound("404 Not Found");
    System.out.println(router);//from  w w  w  .  j  ava 2  s . c om

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

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .channel(NioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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

From source file:Http2Server.java

License:Apache License

public static void main(String... args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from   w w  w . ja  va2  s . co  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey(), null, null,
                Arrays.asList(SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
                0, 0);
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(1);
    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 Http2ServerInitializer(sslCtx));

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

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

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

From source file:adalightserver.http.HttpServer.java

License:Apache License

public void start() {
    ServerBootstrap bootStrap = new ServerBootstrap();
    bootStrap.group(bossGroup, clientGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ServerInitializer(null));

    try {/*  w ww . j a va 2  s  .  com*/
        channel = bootStrap.bind(8081).sync().channel();
    } catch (InterruptedException e) {
    }

    // Listen to the state and send it to all connected clients
    stateSub = ledController.stateChanged().observeOn(scheduler).subscribe(state -> {
        lastState = state;
        wsConnections.writeAndFlush(makeWebSocketEventFrame("stateChanged", state));
    });
}