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:cn.yesway.demo.book.protocol.http.xml.client.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO//from   w  w w . ja va 2 s.c o  m
    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 {
                        ch.pipeline().addLast("http-decoder", new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        // XML?
                        ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
                        ch.pipeline().addLast("http-encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle());
                    }
                });

        // ??
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:cn.yesway.demo.book.protocol.http.xml.server.HttpXmlServer.java

License:Apache License

public void run(final int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w  ww  .j a  va  2s. co  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        ch.pipeline().addLast("xml-decoder", new HttpXmlRequestDecoder(Order.class, true));
                        ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("xml-encoder", new HttpXmlResponseEncoder());
                        ch.pipeline().addLast("xmlServerHandler", new HttpXmlServerHandler());
                    }
                });
        ChannelFuture future = b.bind(new InetSocketAddress(port)).sync();
        System.out.println("HTTP??? : " + "http://localhost:" + port);
        future.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:cn.zyf.ObjectStorageServer.java

License:Open Source License

private void run(String host, int port, int packageSize) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    EventLoopGroup backendGroup = new NioEventLoopGroup();

    try {/* w  w w.  j  ava  2 s  .  c om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(packageSize));
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("oss-decoder", new ParseRequestHandler());
                        ch.pipeline().addLast("oss-filter", new FilterRequestHandler());
                        ch.pipeline().addLast("oss-authen", new AuthenticationHandler());
                        ch.pipeline().addLast("oss-author", new AuthorizationHandler());
                        ch.pipeline().addLast(backendGroup, "oss-backend", new ObjectStorageHandler());
                    }
                });

        ChannelFuture future = b.bind(host, port).sync();
        LOG.info("start Http Server with hostname=" + host + ":" + port);
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOG.error("occur InterruptedException ", e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:co.rsk.net.discovery.UDPServer.java

License:Open Source License

public void startUDPServer() throws InterruptedException {
    logger.info("Discovery UDPListener started");
    EventLoopGroup group = new NioEventLoopGroup(1);

    while (!shutdown) {
        Bootstrap bootstrap = this.createBootstrap(group);

        channel = bootstrap.bind(address, port).sync().channel();
        channel.closeFuture().sync();/*w ww.  j  a  v a2s . c  o m*/

        logger.warn("UDP channel closed. Recreating after 5 sec pause...");
        TimeUnit.SECONDS.sleep(5);
    }
    group.shutdownGracefully().sync();
}

From source file:com.ahanda.techops.noty.clientTest.Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length == 1) {
        System.setProperty("PINT.conf", args[0]);
    }/* w  w w  . ja  v  a  2s.c o m*/

    if (System.getProperty("PINT.conf") == null)
        throw new IllegalArgumentException();

    JsonNode config = null;
    Config cf = Config.getInstance();
    cf.setupConfig();

    String scheme = "http";
    String host = cf.getHttpHost();
    int port = cf.getHttpPort();

    if (port == -1) {
        port = 8080;
    }

    if (!"http".equalsIgnoreCase(scheme)) {
        l.warn("Only HTTP is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec());
                // p.addLast( "decoder", new HttpResponseDecoder());
                // p.addLast( "encoder", new HttpRequestEncoder());

                // Remove the following line if you don't want automatic content decompression.
                // p.addLast(new HttpContentDecompressor());

                // Uncomment the following line if you don't want to handle HttpContents.
                p.addLast(new HttpObjectAggregator(10485760));

                p.addLast(new ClientHandler());
            }
        });

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

        ClientHandler client = new ClientHandler();
        client.login(ch, ClientHandler.credential);
        // ClientHandler.pubEvent( ch, ClientHandler.event );

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
        l.info("Closing Client side Connection !!!");
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:com.alltobid.quotabid.BidClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    bidClientHandler.addListener(new BidClientHandlerAdapter() {
        @Override/*from w w w.j av a 2s. com*/
        public void messageReceived(ReceivedMessage receivedMessage) {
            receivedMessageQueue.add(receivedMessage);
        }
    });

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new BidClientInitializer());

        MonitorThread monitorThread = new MonitorThread();
        monitorThread.setName("BidClient Monitor");
        monitorThread.start();

        while (true) {
            try {
                // Start the client.
                Channel ch = b.connect(HOST, PORT).sync().channel();

                // Wait until the connection is closed.
                ch.closeFuture().sync();
            } catch (Exception ex) {
                logger.error("Channel Error", ex);
                Thread.sleep(5000);
            }
        }
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.artigile.homestats.HomeStatsServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    ArgsParser argsParser = new ArgsParser(args);
    if (argsParser.isDisplayHelp()) {
        ArgsParser.printHelp();//from   ww w.ja  v  a  2 s . co  m
        return;
    }

    EventLoopGroup bossGroup = null;
    EventLoopGroup workerGroup = null;
    try {
        SensorMode appMode = SensorMode
                .valueOf(argsParser.getString(ArgsParser.APP_MODE_OPTION, "dev").toUpperCase());

        SensorsDataProvider sensorsDataProvider = SensorFactory.buildSensorDataProvider(appMode);
        if (sensorsDataProvider == null) {
            LOGGER.error("No sensor device available, quitting.");
            return;
        }

        final boolean printAndExit = argsParser.argumentPassed(ArgsParser.PRINT_AND_EXIT);
        if (printAndExit) {
            sensorsDataProvider.printAll();
            return;
        }

        final String dbHost = argsParser.getString(DB_HOST_OPTION, "localhost");
        final String user = argsParser.getString(DB_USER_OPTION);
        final String pwd = argsParser.getString(DB_PWD_OPTION);
        final int port = Integer.valueOf(argsParser.getString(APP_PORT_OPTION, PORT + ""));

        LOGGER.info("Connecting to {}, user {}, pwd: {}", dbHost, user, pwd);
        final DbDao dbDao = new DbDao(dbHost, user, pwd);
        new DataService(sensorsDataProvider, dbDao, 1000 * 60 * 5).start();

        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } else {
            sslCtx = null;
        }

        // Configure the server.
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new HomeStatsServerInitializer(sslCtx, dbDao, sensorsDataProvider));

        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 {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
}

From source file:com.athena.dolly.websocket.server.test.WebSocketServer.java

License:Apache License

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

        Channel ch = b.bind(port).sync().channel();
        System.out.println("Web socket server started 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:com.athena.dolly.websocket.server.test.WebSocketSslServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//www  .  j a  v  a 2 s  . c  om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketSslServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port + '.');
        System.out.println("Open your browser and navigate to https://localhost:" + port + '/');
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.baidu.rigel.biplatform.ma.file.client.service.impl.FileServerClient.java

License:Open Source License

/**
 * ?//from   w w w  . j  a  v a2 s  . c  o m
 * 
 * @param server
 *            ??
 * @param port
 *            ??
 * @param request
 *            
 * @return 
 */
public Response doRequest(String server, int port, final Request request) {
    EventLoopGroup work = new NioEventLoopGroup(1);
    String message = null;
    try {
        final Response rs = new Response(ResponseStatus.FAIL, "failed", null);
        ChannelHandlerAdapter requestHandler = new ChannelHandlerAdapter() {

            /**
             * {@inheritDoc}
             */
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                logger.info("successfully connect to file server");
                ctx.write(request);
                ctx.flush();
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                logger.info("successfuly recieve message from file server {}", msg);
                Response tmpRs = (Response) msg;
                rs.setDatas(tmpRs.getDatas());
                rs.setMessage(tmpRs.getMessage());
                rs.setStatus(tmpRs.getStatus());
                ctx.close();
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                ctx.flush();
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                logger.error(cause.getMessage());
                rs.setMessage(cause.getMessage());
                rs.setStatus(ResponseStatus.FAIL);
                ctx.close();
            }
        };
        Bootstrap strap = new Bootstrap();
        strap.group(work).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel chl) throws Exception {
                        // ??
                        chl.pipeline().addLast(new ObjectDecoder(
                                ClassResolvers.cacheDisabled(requestHandler.getClass().getClassLoader())));
                        chl.pipeline().addLast(new ObjectEncoder());
                        chl.pipeline().addLast(requestHandler);
                    }

                });
        long begin = System.currentTimeMillis();
        logger.debug("Begin invoke do file operation request ... ...");
        ChannelFuture future = strap.connect(server, port);
        future.channel().closeFuture().sync();
        logger.debug(
                "Success execute request option cost time: " + (System.currentTimeMillis() - begin) + "ms");
        return rs;
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
        message = e.getMessage();
    } finally {
        work.shutdownGracefully();
    }
    Response rs = new Response(ResponseStatus.FAIL, message, null);
    return rs;
}