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.cmz.stomp.StompClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*w  w  w . j a va2  s. co m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new StompSubframeDecoder());
                pipeline.addLast("encoder", new StompSubframeEncoder());
                pipeline.addLast("aggregator", new StompSubframeAggregator(1048576));
                pipeline.addLast("handler", new StompClientHandler());
            }
        });

        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.InboundWebSocketConnection.java

License:Apache License

/**
 * {@inheritDoc}//from  w  w  w.ja va2 s . c  o m
 */
@Override
public void start(final ConnectionConfig config) {
    URI endpoint = URI.create(config.getEndpoint());

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    connectedChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(
            new WebSocketServerInitializer(endpoint, connectionMonitor, config, connectedChannels));

    try {
        serverBootstrap.bind(endpoint.getPort()).sync().channel();
        LOG.info("Web socket server started at port {}.", endpoint.getPort());
    } catch (InterruptedException e) {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

        throw new IllegalStateException("Error starting web socket endpoint.", e);
    }
}

From source file:com.creamsugardonut.HttpStaticFileServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("available cores : " + Runtime.getRuntime().availableProcessors() * 2);
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w  w w  . j av  a2  s  .  c o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpStaticFileServerInitializer());
        Channel ch = b.bind(PORT).sync().channel();
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.crystal.chat.SecureChatClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();//ww w  .j a  va  2 s  . c om

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx));
        // Start the connection attempt.
        Channel ch = b.connect(HOST, Port.PORT).sync().channel();

        //send name and rtmpurl
        /* JSONObject obj = new JSONObject();
         String uuid = UUID.randomUUID()+"";
         obj.put("name", uuid);
         obj.put("rtmpurl", "rtmp://s2.weiqu168.com/live/"+uuid);
         ch.writeAndFlush(obj.toString());*/

        // 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;
            }
            JSONObject obj = new JSONObject();
            String uuid = UUID.randomUUID() + "";
            obj.put("action", "Set");
            obj.put("name", uuid);
            obj.put("rtmp", "rtmp://xxxx.com/live/" + uuid);
            // Sends the received line to the server.1
            lastWriteFuture = ch.writeAndFlush(obj.toString() + "\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 {
        // The connection is closed automatically on shutdown.
        group.shutdownGracefully();
    }
}

From source file:com.crystal.chat.SecureChatServer.java

License:Apache License

public static void main(String[] args) 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 {//from w w w.j  a  v  a 2s. c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)

                .channel(NioServerSocketChannel.class).option(ChannelType.op, ChannelType.TYPE_TCP)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SecureChatServerInitializer(sslCtx));

        ChannelFuture future = b.bind("127.0.0.1", Port.PORT).sync().channel().closeFuture().sync();

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.ctrip.xpipe.redis.console.health.netty.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {/*from  ww w. j ava2 s.  co m*/
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT);
        Channel c = f.channel();

        while (true) {
            ByteBuf buf = Unpooled.buffer(8);
            buf.writeLong(System.nanoTime());
            c.writeAndFlush(buf);
            Thread.sleep(1000);
        }

    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.ctrip.xpipe.redis.console.health.netty.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from www .j a va 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).option(ChannelOption.TCP_NODELAY, true)
                .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.
        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.datastax.driver.core.NettyOptions.java

License:Apache License

/**
 * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
 * <p/>/*from  w w w.j  a va2s  .  com*/
 * This is guaranteed to be called only after all connections have been individually
 * closed, and their channels closed, and only once per {@link EventLoopGroup} instance.
 * <p/>
 * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required.
 * <p/>
 * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully() graceful shutdown}
 * of the passed {@link EventLoopGroup}, then waits uninterruptibly for the shutdown to complete or timeout.
 * <p/>
 * Implementation note: if the {@link EventLoopGroup} instance is being shared, or used for other purposes than to
 * coordinate Netty events for the current cluster, then it should not be shut down here;
 * subclasses would have to override this method accordingly to take the appropriate action.
 *
 * @param eventLoopGroup the event loop group used by the cluster being closed
 */
public void onClusterClose(EventLoopGroup eventLoopGroup) {
    eventLoopGroup.shutdownGracefully().syncUninterruptibly();
}

From source file:com.demo.netty.echo.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from   w  ww.  ja  v a  2 s.  com
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    //EventLoopGroup is  abstraction of Notification and Thread loop
    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.
        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.digisky.innerproxy.server.HttpServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    ProcessServerManager.getInstance().init();
    final SslContext sslCtx;
    if (SSL) {// w ww  .  ja va 2 s . c  om
        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)
                //.handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpServerInitializer(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();
    }
}