Example usage for io.netty.channel EventLoopGroup shutdownGracefully

List of usage examples for io.netty.channel EventLoopGroup shutdownGracefully

Introduction

In this page you can find the example usage for io.netty.channel EventLoopGroup shutdownGracefully.

Prototype

Future<?> shutdownGracefully();

Source Link

Document

Shortcut method for #shutdownGracefully(long,long,TimeUnit) with sensible default values.

Usage

From source file:com.github.nettybook.ch8.HttpSnoopServer.java

License:Apache License

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

    try {
        File certChainFile = new File("netty.crt");
        File keyFile = new File("privatekey.pem");
        keyFile.exists();

        sslCtx = SslContext.newServerContext(certChainFile, keyFile, "1234");
    } 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:com.github.nettybook.ch8.TelnetServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   www .  j  av  a  2 s  . co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new TelnetServerInitializer());

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

From source file:com.github.sinsinpub.pero.frontend.NettySocksServer.java

License:Apache License

public void run() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1, ThreadFactoryRepository.BOSS_GORUP);
    EventLoopGroup workerGroup = new NioEventLoopGroup(getMaxWorkerThreads(),
            ThreadFactoryRepository.WORKER_GROUP);
    try {/* w  ww.  ja  va 2s .  c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(getSocksServerInitializer());
        ChannelFuture cf = b.bind(getPort()).sync();
        logger.info(
                String.format("Proxy server %s %s started.", ApplicationVersion.DEFAULT.getApplicationName(),
                        ApplicationVersion.DEFAULT.getApplicationVersion()));
        cf.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.unafraid.signer.server.ServerManager.java

License:Apache License

private void init() {
    SslContext sslCtx = null;/*from  w ww . j  a v  a  2s  .c o m*/
    if (SSL) {
        try {
            final SelfSignedCertificate ssc = new SelfSignedCertificate("localhost");
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (Exception e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }

    InetAddress listenAddress;
    try {
        listenAddress = Inet4Address.getByName(HOSTNAME);
    } catch (Exception e) {
        LOGGER.warn("Incorrect listen ip specified: {} using localhost instead!", HOSTNAME);
        listenAddress = Inet4Address.getLoopbackAddress();
    }
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        final ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ServerInitializer(sslCtx));

        // Start listening
        final Channel ch = b.bind(listenAddress, PORT).sync().channel();

        LOGGER.info("Open your web browser and navigate to {}://{}{}/", (SSL ? "https" : "http"),
                listenAddress.getHostAddress(), (PORT != 443 && PORT != 80 ? ":" + PORT : ""));

        // Block til closed
        ch.closeFuture().sync();

    } catch (Exception e) {
        LOGGER.warn("Failed to initialize server: ", e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServer.java

License:Open Source License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from ww  w  . ja  v a2 s.co  m*/
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

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

        // 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.github.wangshuwei5.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO/*from w w w.j  a  v a  2s  . c  o  m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    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 NettyServerInitializer(SSLMODE.CSA.toString()));

        // ???
        ChannelFuture f = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();

        // ???
        f.channel().closeFuture().sync();

        System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.guowl.websocket.client.WebSocketClientRunner.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from  w w w .  j a va2  s  . com
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        final String protocol = uri.getScheme();
        int defaultPort;
        ChannelInitializer<SocketChannel> initializer;

        // Normal WebSocket
        if ("ws".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 80;
            // Secure WebSocket
        } else if ("wss".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    SSLEngine engine = WebSocketSslClientContextFactory.getContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addFirst("ssl", new SslHandler(engine))
                            .addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 443;
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(initializer);

        int port = uri.getPort();
        // If no port was specified, we'll try the default port: https://tools.ietf.org/html/rfc6455#section-1.7
        if (uri.getPort() == -1) {
            port = defaultPort;
        }

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.guowl.websocket.stream.client.StreamClientRunner.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*  w  w  w.  j  av  a2 s .c  o m*/
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08
        // or V00.
        // If you change it to V00, ping is not supported and remember to
        // change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the
        // pipeline.
        final StreamClientHandler handler = new StreamClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        final String protocol = uri.getScheme();
        int defaultPort;
        ChannelInitializer<SocketChannel> initializer;

        // Normal WebSocket
        if ("ws".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 80;
            // Secure WebSocket
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(initializer);

        int port = uri.getPort();
        // If no port was specified, we'll try the default port:
        if (uri.getPort() == -1) {
            port = defaultPort;
        }

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();
        ByteBuf dataBuf = ch.alloc().buffer();
        dataBuf.writeBytes("start".getBytes());
        ch.writeAndFlush(new BinaryWebSocketFrame(false, 0, dataBuf));
        ch.writeAndFlush(new ContinuationWebSocketFrame(true, 0, "end"));
        Thread.sleep(1000 * 60 * 60);
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.gw.monitor.alphaenvmonitor.monitor.MonitorClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/* w ww.java2 s .c  o m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new MonitorClientInitializer());

        // Start the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");

            // If user typed the 'bye' command, wait until the server closes
            // the connection.
            if ("bye".equals(line.toLowerCase())) {
                ch.closeFuture().sync();
                break;
            }
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.gw.monitor.alphaenvmonitor.monitor.MonitorServer.java

License:Apache License

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

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