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.my.netty.object.ObjectEchoServer.java

License:Apache License

public void run() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//ww  w  .j  a va2  s.c o  m
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline cp = ch.pipeline();
                        cp.addLast(new ObjectEncoder());
                        cp.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                        cp.addLast(new ObjectEchoServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        System.out.println("server prepare staring");
        b.bind(port).sync().channel().closeFuture().sync();
        System.out.println("server start ok");
    } finally {
        System.out.println("server  do finally");
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        System.out.println("server closing ok");
    }
}

From source file:com.mycompany.nettyweb.HttpServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w  ww. j  a  v a 2  s . c  om*/
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer());

        Channel ch = bootstrap.bind(port).sync().channel();
        System.out.println("Server started, port:" + port);
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.mylearn.netty.sample.websocket.client.WebSocketClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from w  w  w  . ja v  a2 s  .  c  o  m
        Bootstrap b = new Bootstrap();
        String protocol = uri.getScheme();
        if (!"ws".equals(protocol)) {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        HttpHeaders customHeaders = new DefaultHttpHeaders();
        customHeaders.add("MyHeader", "MyValue");

        // 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, customHeaders));

        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("http-codec", new HttpClientCodec());
                pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
                pipeline.addLast("ws-handler", handler);
            }
        });

        System.out.println("WebSocket Client connecting");
        Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        handler.handshakeFuture().sync();

        // Send 10 messages and wait for responses
        System.out.println("WebSocket Client sending message");
        for (int i = 0; i < 10; i++) {
            ch.writeAndFlush(new TextWebSocketFrame("Message #" + i));
        }

        // Ping
        System.out.println("WebSocket Client sending ping");
        ch.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));

        // Close
        System.out.println("WebSocket Client sending close");
        ch.writeAndFlush(new CloseWebSocketFrame());

        // WebSocketClientHandler will close the connection when the server
        // responds to the CloseWebSocketFrame.
        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.myseti.framework.monitor.net.MonitorServer.java

@Override
public void run() {
    try {/*  www .j a v a2s . c om*/
        // Configure SSL.
        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 MonitorServerHandler()).childHandler(new MonitorServerInitializer(sslCtx));

            b.bind(PORT).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    } catch (Exception ex) {

    }
    super.run(); //To change body of generated methods, choose Tools | Templates.
}

From source file:com.netflix.hystrix.examples.reactivesocket.HystrixMetricsReactiveSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("Starting HystrixMetricsReactiveSocketServer...");

    final ReactiveSocketServerHandler handler = ReactiveSocketServerHandler
            .create((setupPayload, rs) -> new EventStreamRequestHandler());

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

    try {/*  www  .  ja v  a  2 s .co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(handler);
                    }
                });
        Channel localhost = b.bind("127.0.0.1", 8025).sync().channel();

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

From source file:com.netty.file.HttpUploadServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from www. j  av a  2  s . com*/
        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);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(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:com.netty.fileTest.file.FileReaderClient.java

License:Apache License

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

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   w  ww .  j a  v a2  s.c  om*/
        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();
                        p.addLast(new FileReaderClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect("127.0.0.1", 8007).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.netty.fileTest.file.FileSenderServer.java

License:Apache License

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

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// w w  w  .  j a va 2  s.  c o m
        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();
                        p.addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(8192),
                                new StringDecoder(CharsetUtil.UTF_8), new ChunkedWriteHandler(),
                                new FileSenderServerHandler());
                    }
                });

        // 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.netty.fileTest.http.download.HttpStaticFileServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*  w  w  w. jav a 2s  .  co  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(SslProvider.JDK, 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(LogLevel.INFO))
                .childHandler(new HttpStaticFileServerInitializer(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();
    }
}

From source file:com.netty.fileTest.http.upload.HttpUploadClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    String postFile;/*from   www .j  av  a2  s .  co m*/
    // postFile = BASE_URL + "formpost";
    postFile = BASE_URL + "formpostmultipart";
    URI uriFile = new URI(postFile);
    File file = new File(FILE);
    if (!file.canRead()) {
        throw new FileNotFoundException(FILE);
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(null));

    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
    // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    try {
        ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
        // Wait until the connection attempt succeeds or fails.
        Channel channel = future.sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                uriFile.toASCIIString());
        // Use the PostBody encoder
        HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false);
        // add Form attribute
        bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

        // finalize request
        request = bodyRequestEncoder.finalizeRequest();

        // Create the bodylist to be reused on the last version with Multipart support
        List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

        // send request
        channel.write(request);

        // test if request was chunked and if so, finish the write
        if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
            channel.write(bodyRequestEncoder);
        }
        channel.flush();
        channel.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();

        // Really clean all temporary files if they still exist
        factory.cleanAllHttpDatas();
    }
}