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.changxx.phei.netty.protocol.netty.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIOse/*from   w w w  .  ja  v a 2  s. co m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    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 IOException {
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                    ch.pipeline().addLast(new NettyMessageEncoder());
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new LoginAuthRespHandler());
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
                }
            });

    // ???
    b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
}

From source file:com.chen.opensourceframework.netty.copy.DiscardServer.java

License:Apache License

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

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from www.ja  v a 2  s  .  c  o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6);

        ChannelFuture f = b.bind(PORT).sync();

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

From source file:com.chen.opensourceframework.netty.discard.DiscardServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from w w  w  .  j a  v a2s . 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)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new DiscardServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.chenyang.proxy.EchoServer.java

License:Apache License

public static void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from ww  w .  j  a v  a2 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)
                .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));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        System.out.println(" server start in port " + PORT);
        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:com.chenyang.proxy.http.HttpServer.java

License:Apache License

public void start() {
    int port = Constants.Http.PORT;

    logger.info("ApnProxy Server Listen on: " + port);

    ServerBootstrap serverBootStrap = new ServerBootstrap();

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

    try {//from  ww  w  .ja  v  a 2 s . co  m
        serverBootStrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port)
                .childHandler(new HttpServerChannelInitializer());
        serverBootStrap.bind().sync().channel().closeFuture().sync();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        logger.error("showdown the server");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.chiorichan.net.NetworkManager.java

License:Mozilla Public License

public static void startHttpServer() throws StartupException {
    if (httpChannel != null && httpChannel.isOpen())
        throw new StartupException("The HTTP Server is already running");

    try {//from ww w. j  a v a  2 s . c  o  m
        InetSocketAddress socket;
        String httpIp = AppConfig.get().getString("server.httpHost", "");
        int httpPort = AppConfig.get().getInt("server.httpPort", 8080);

        if (httpPort > 0) {
            if (Application.isPrivilegedPort(httpPort)) {
                getLogger().warning(
                        "It would seem that you are trying to start ChioriWebServer's Web Server on a privileged port without root access.");
                getLogger().warning(
                        "Most likely you will see an exception thrown below this. http://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html");
                getLogger().warning(
                        "It's recommended that you either run CWS on a port like 8080 then use the firewall to redirect from 80 or run as root if you must use port: "
                                + httpPort);
            }

            if (httpIp.isEmpty())
                socket = new InetSocketAddress(httpPort);
            else
                socket = new InetSocketAddress(httpIp, httpPort);

            // TODO Allow the server to bind to more than one IP

            getLogger().info("Starting Web Server on " + (httpIp.isEmpty() ? "*" : httpIp) + ":" + httpPort);

            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .childHandler(new HttpInitializer());

                httpChannel = b.bind(socket).sync().channel();

                // HTTP Server Thread
                AppController.registerRunnable(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            httpChannel.closeFuture().sync();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        getLogger().info("The HTTP Server has been shutdown!");
                    }
                });
            } catch (NullPointerException e) {
                throw new StartupException(
                        "There was a problem starting the Web Server. Check logs and try again.", e);
            } catch (Throwable e) {
                getLogger().warning("**** FAILED TO BIND HTTP SERVER TO PORT!");
                // getLogger().warning( "The exception was: {0}", new Object[] {e.toString()} );
                getLogger().warning("Perhaps a server is already running on that port?");

                throw new StartupException(e);
            }
        } else
            getLogger().warning("The HTTP server is disabled per configs.");
    } catch (Throwable e) {
        if (e instanceof StartupException)
            throw e;
        else
            throw new StartupException(e);
    }
}

From source file:com.chiorichan.net.NetworkManager.java

License:Mozilla Public License

public static void startHttpsServer() throws StartupException {
    if (httpsChannel != null && httpsChannel.isOpen())
        throw new StartupException("The HTTPS Server is already running");

    try {/*from   ww  w  .j av  a  2s .  c  om*/
        InetSocketAddress socket;
        String httpIp = AppConfig.get().getString("server.httpHost", "");
        int httpsPort = AppConfig.get().getInt("server.httpsPort", 8443);

        Security.addProvider(new BouncyCastleProvider());

        if (httpsPort >= 1) {
            if (Application.isPrivilegedPort(httpsPort)) {
                getLogger().warning(
                        "It would seem that you are trying to start ChioriWebServer's Web Server (SSL) on a privileged port without root access.");
                getLogger().warning(
                        "Most likely you will see an exception thrown below this. http://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html");
                getLogger().warning(
                        "It's recommended that you either run CWS (SSL) on a port like 4443 then use the firewall to redirect from 443 or run as root if you must use port: "
                                + httpsPort);
            }

            if (httpIp.isEmpty())
                socket = new InetSocketAddress(httpsPort);
            else
                socket = new InetSocketAddress(httpIp, httpsPort);

            AppManager.manager(SslManager.class).init();

            getLogger().info(
                    "Starting Secure Web Server on " + (httpIp.isEmpty() ? "*" : httpIp) + ":" + httpsPort);

            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .childHandler(new SslInitializer());

                httpsChannel = b.bind(socket).sync().channel();

                // HTTPS Server Thread
                AppController.registerRunnable(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            httpsChannel.closeFuture().sync();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        getLogger().info("The HTTPS Server has been shutdown!");
                    }
                });
            } catch (NullPointerException e) {
                throw new StartupException(
                        "There was a problem starting the Web Server. Check logs and try again.", e);
            } catch (Throwable e) {
                getLogger().warning("**** FAILED TO BIND HTTPS SERVER TO PORT!");
                getLogger().warning("Perhaps a server is already running on that port?");

                throw new StartupException(e);
            }
        } else
            getLogger().warning("The HTTPS server is disabled per configs.");
    } catch (Throwable e) {
        throw new StartupException(e);
    }
}

From source file:com.chiorichan.net.NetworkManager.java

License:Mozilla Public License

public static void startQueryServer() throws StartupException {
    if (queryChannel != null && queryChannel.isOpen())
        throw new StartupException("The Query Server is already running");

    try {/*from   w  ww . ja va 2s. co m*/
        InetSocketAddress socket;
        String queryHost = AppConfig.get().getString("server.queryHost", "");
        int queryPort = AppConfig.get().getInt("server.queryPort", 8992);

        if (queryPort >= 1 && AppConfig.get().getBoolean("server.queryEnabled")) {
            if (Application.isPrivilegedPort(queryPort)) {
                getLogger().warning(
                        "It would seem that you are trying to start the Query Server on a privileged port without root access.");
                getLogger().warning(
                        "Most likely you will see an exception thrown below this. http://www.w3.org/Daemon/User/Installation/PrivilegedPorts.html");
                getLogger().warning(
                        "It's recommended that you either run CWS on a port like 8080 then use the firewall to redirect or run as root if you must use port: "
                                + queryPort);
            }

            if (queryHost.isEmpty())
                socket = new InetSocketAddress(queryPort);
            else
                socket = new InetSocketAddress(queryHost, queryPort);

            getLogger().info(
                    "Starting Query Server on " + (queryHost.isEmpty() ? "*" : queryHost) + ":" + queryPort);

            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .childHandler(new QueryServerInitializer());

                queryChannel = b.bind(socket).sync().channel();

                // Query Server Thread
                AppController.registerRunnable(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            queryChannel.closeFuture().sync();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        getLogger().info("The Query Server has been shutdown!");
                    }
                });
            } catch (NullPointerException e) {
                throw new StartupException(
                        "There was a problem starting the Web Server. Check logs and try again.", e);
            } catch (Throwable e) {
                getLogger().warning("**** FAILED TO BIND QUERY SERVER TO PORT!");
                getLogger().warning("Perhaps a server is already running on that port?");

                throw new StartupException(e);
            }
        }
    } catch (Throwable e) {
        throw new StartupException(e);
    }
}

From source file:com.chschmid.huemorse.server.HueMorse.java

License:Open Source License

/**
 * Start server huemorse server/*from ww w.  j ava  2 s  .  c o  m*/
 */
private static void startServers() throws Exception {
    if (DEBUG)
        System.out.println("Starting servers");

    EventLoopGroup bossGroupHueMorse = new NioEventLoopGroup();
    EventLoopGroup workerGroupHueMorse = new NioEventLoopGroup();

    try {
        ServerBootstrap huemorse = new ServerBootstrap();

        huemorse.group(bossGroupHueMorse, workerGroupHueMorse).channel(NioServerSocketChannel.class)
                .childHandler(new MorseServerInitializer(hue));

        huemorse.bind(SERVER_PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroupHueMorse.shutdownGracefully();
        workerGroupHueMorse.shutdownGracefully();
    }
}

From source file:com.chschmid.pilight.server.PILight.java

License:Open Source License

/**
 * Starts who servers for pimorse and the more direct piglight interface
 * @param  light the PiLightInterface to operate on.
 *///from   w  w  w.  j  av a  2 s . c o  m
private static void startServers(PiLightInterface light) throws Exception {
    if (DEBUG)
        System.out.println("Starting servers");
    light.start();

    EventLoopGroup bossGroupPiLight = new NioEventLoopGroup();
    EventLoopGroup workerGroupPiLight = new NioEventLoopGroup();
    EventLoopGroup bossGroupPiMorse = new NioEventLoopGroup();
    EventLoopGroup workerGroupPiMorse = new NioEventLoopGroup();

    try {
        ServerBootstrap pilight = new ServerBootstrap();
        ServerBootstrap pimorse = new ServerBootstrap();

        pilight.group(bossGroupPiLight, workerGroupPiLight).channel(NioServerSocketChannel.class)
                .childHandler(new LightServerInitializer(light));

        pimorse.group(bossGroupPiMorse, workerGroupPiMorse).channel(NioServerSocketChannel.class)
                .childHandler(new MorseServerInitializer(light));

        pilight.bind(LIGHT_SERVER_PORT).sync();
        pimorse.bind(MORSE_SERVER_PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroupPiLight.shutdownGracefully();
        workerGroupPiLight.shutdownGracefully();
        bossGroupPiMorse.shutdownGracefully();
        workerGroupPiMorse.shutdownGracefully();
    }

    light.stop();
}