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.vip.netty.basic.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/*from   w  w  w  . ja  va2s  .co  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, 1024).childHandler(new ChildChannelHandler());
        // ???
        ChannelFuture f = b.bind(port).sync();

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

    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.vip.netty.protocol.file.FileServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  w  ww.  j a  v a 2 s.co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    /*
                     * (non-Javadoc)
                     *
                     * @see
                     * io.netty.channel.ChannelInitializer#initChannel(io
                     * .netty.channel.Channel)
                     */
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8),
                                new FileServerHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        System.out.println("Start file server at port : " + port);
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.vip.netty.protocol.http.fileServer.HttpFileServer.java

License:Apache License

public void run(final int port, final String url) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    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)
                .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("http-encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url));
                    }
                });
        ChannelFuture future = b.bind("192.168.0.106", port).sync();
        System.out.println(
                "HTTP??? : " + "http://192.168.0.106:" + port + url);
        future.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.wangsan.study.netty.codec.serializable.netty.SubReqClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO//from   w  w w. ja v  a 2  s  .  co  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(
                                // max?
                                new ObjectDecoder(1024,
                                        ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
                        ch.pipeline().addLast(new ObjectEncoder());
                        ch.pipeline().addLast(new SubReqClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();

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

From source file:com.weibo.yar.yarserver.NettyYarServer.java

License:Apache License

public void start(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w  w  w  .j a  v a 2  s .c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        ch.pipeline().addLast("serverHandler", new HttpServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true);

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

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

From source file:com.whirvis.jraknet.RakNet.java

License:Open Source License

/**
 * Sends a packet to the specified address.
 * /*from  ww  w  .  j a v  a2  s .  com*/
 * @param address
 *            the address to send the packet to.
 * @param packet
 *            the packet to send.
 * @param timeout
 *            how long to wait until resending the packet.
 * @param retries
 *            how many times the packet will be sent before giving up.
 * @return the packet received in response, <code>null</code> if no response
 *         was received or the thread was interrupted.
 * @throws NullPointerException
 *             if the <code>address</code>, IP address of the
 *             <code>address</code>, or <code>packet</code> are
 *             <code>null</code>.
 * @throws IllegalArgumentException
 *             if the <code>timeout</code> or <code>retries</code> are less
 *             than or equal to <code>0</code>.
 */
private static RakNetPacket createBootstrapAndSend(InetSocketAddress address, Packet packet, long timeout,
        int retries) throws NullPointerException, IllegalArgumentException {
    if (address == null) {
        throw new NullPointerException("Address cannot be null");
    } else if (address.getAddress() == null) {
        throw new NullPointerException("IP address cannot be null");
    } else if (packet == null) {
        throw new NullPointerException("Packet cannot be null");
    } else if (timeout <= 0) {
        throw new IllegalArgumentException("Timeout must be greater than 0");
    } else if (retries <= 0) {
        throw new IllegalArgumentException("Retriest must be greater than 0");
    }

    // Prepare bootstrap
    RakNetPacket received = null;
    EventLoopGroup group = new NioEventLoopGroup();
    int maximumTransferUnit = getMaximumTransferUnit();
    if (maximumTransferUnit < MINIMUM_MTU_SIZE) {
        return null;
    }
    try {
        // Create bootstrap
        Bootstrap bootstrap = new Bootstrap();
        BootstrapHandler handler = new BootstrapHandler();
        bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, maximumTransferUnit)
                .option(ChannelOption.SO_SNDBUF, maximumTransferUnit).handler(handler);
        Channel channel = bootstrap.bind(0).sync().channel();

        // Wait for response
        while (retries > 0 && received == null && !Thread.currentThread().isInterrupted()) {
            long sendTime = System.currentTimeMillis();
            channel.writeAndFlush(new DatagramPacket(packet.buffer(), address));
            while (System.currentTimeMillis() - sendTime < timeout && handler.packet == null)
                ; // Wait for either a timeout or a response
            received = handler.packet;
            retries--;
        }
    } catch (InterruptedException e) {
        return null;
    }
    group.shutdownGracefully();
    return received;
}

From source file:com.witjit.game.client.Client.java

License:Apache License

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

    EventLoopGroup group = new NioEventLoopGroup();
    try {/* w  w w. j  a  v a  2s .c  o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer());

        // 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;
        //                }
        //            }

        ByteBuf outb = Unpooled.buffer(200);
        outb.writeShort(127);
        outb.writeShort(10);
        outb.writeInt(10001);
        outb.writeByte(40);
        outb.writeByte(50);
        // Sends the received line to the server.
        lastWriteFuture = ch.writeAndFlush(outb);
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }

        // Wait until the connection is closed.
        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.witjit.game.client.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {/*  ww w .j  a v a2  s  . c o  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).sync();

        sendData(f.channel());

        // 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.wuma.file.FileServer.java

License:Apache License

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

    // 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 StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(8192),
                                new StringDecoder(CharsetUtil.UTF_8), new ChunkedWriteHandler(),
                                new FileServerHandler());
                    }
                });

        // 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.wx3.galacdecks.networking.NettyWebSocketServer.java

License:Open Source License

public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   ww w  .  j  av a 2  s.  c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new WebSocketServerInitializer(this, null));

        Channel ch = b.bind(port).sync().channel();
        // This blocks until the channel is closed:
        ch.closeFuture().sync();

    } catch (InterruptedException e) {
        // What do we do with an interupted exception?
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}