Example usage for io.netty.channel.nio NioEventLoopGroup shutdownGracefully

List of usage examples for io.netty.channel.nio NioEventLoopGroup shutdownGracefully

Introduction

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

Prototype

@Override
    public Future<?> shutdownGracefully() 

Source Link

Usage

From source file:io.aos.netty5.udt.echo.bytes.ByteEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    ExecutorServiceFactory acceptFactory = new DefaultExecutorServiceFactory("accept");
    ExecutorServiceFactory connectFactory = new DefaultExecutorServiceFactory("connect");
    NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.BYTE_PROVIDER);
    NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER);

    // Configure the server.
    try {// www .j  a  va2 s .  c  o m
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoServerHandler());
                    }
                });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

From source file:io.aos.netty5.udt.echo.message.MsgEchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure the client.
    final ExecutorServiceFactory connectFactory = new DefaultExecutorServiceFactory("connect");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.MESSAGE_PROVIDER);

    try {/*from ww  w.java  2s . c o  m*/
        final Bootstrap boot = new Bootstrap();
        boot.group(connectGroup).channelFactory(NioUdtProvider.MESSAGE_CONNECTOR)
                .handler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoClientHandler());
                    }
                });
        // Start the client.
        final ChannelFuture f = boot.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        connectGroup.shutdownGracefully();
    }
}

From source file:io.aos.netty5.udt.echo.message.MsgEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    final ExecutorServiceFactory acceptFactory = new DefaultExecutorServiceFactory("accept");
    final ExecutorServiceFactory connectFactory = new DefaultExecutorServiceFactory("connect");
    final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory,
            NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.MESSAGE_PROVIDER);

    // Configure the server.
    try {/*from w w w . j  a va2s  .com*/
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.MESSAGE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoServerHandler());
                    }
                });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

From source file:io.aos.netty5.udt.echo.rendezvous.MsgEchoPeerBase.java

License:Apache License

public void run() throws Exception {
    // Configure the peer.
    final ExecutorServiceFactory connectFactory = new DefaultExecutorServiceFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.MESSAGE_PROVIDER);

    try {// w w  w . ja  v  a 2 s  .  co  m
        final Bootstrap boot = new Bootstrap();
        boot.group(connectGroup).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
                .handler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO),
                                new MsgEchoPeerHandler(messageSize));
                    }
                });
        // Start the peer.
        final ChannelFuture f = boot.connect(peer, self).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        connectGroup.shutdownGracefully();
    }
}

From source file:io.aos.netty5.udt.echo.rendezvousBytes.ByteEchoPeerBase.java

License:Apache License

public void run() throws Exception {
    final ExecutorServiceFactory connectFactory = new DefaultExecutorServiceFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.BYTE_PROVIDER);

    try {//from w ww.j  ava2  s.  c o m
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(connectGroup).channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
                .handler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    protected void initChannel(UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO),
                                new ByteEchoPeerHandler(messageSize));
                    }
                });
        final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync();
        future.channel().closeFuture().sync();
    } finally {
        connectGroup.shutdownGracefully();
    }
}

From source file:me.ferrybig.javacoding.teamspeakconnector.TeamspeakConnectionIT.java

@Test
public void testSomeMethod() throws InterruptedException, ExecutionException {
    Logger.getGlobal().getParent().setLevel(Level.ALL);
    Logger.getLogger(TeamspeakConnection.class.getName()).setLevel(Level.ALL);
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {/*w  w  w . ja va 2 s  .co m*/
        System.out.println("Creating!");
        TeamspeakApi api = new TeamspeakApi(group);
        Future<TeamspeakConnection> connect = api.connect(new InetSocketAddress("127.0.0.1", 10011),
                "serveradmin", "test1234");

        System.out.println("Connected!");
        TeamspeakConnection con = connect.sync().get();

        System.out.println("Selecting server!");
        con.getUnresolvedServerById(1).select().sync().get();

        System.out.println("Creating!");
        con.getServer();
        con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();
        //         con.getServer();

        System.out.println("Queue make!");
        System.out.println(con.getServer().sync().get());

        System.out.println("Username seting....");
        con.setOwnName("TestingBot").sync().get();

        System.out.println("User list!");
        List<User> users = con.getUsersList().sync().get();
        for (User user : users) {
            if (user.getType() == ClientType.QUERY) {
                continue;
            }
            user.poke("Hello: " + user.getNickname() + ", Your ip address: " + user.getIp());
            user.sendMessage("Hello: " + user.getNickname() + ", Your ip address: " + user.getIp());
        }

        System.out.println("Waiting for messages!");
        con.getPrivateMessageHandler().addHandler(evt -> {
            System.out.println("Message received! " + evt);
            evt.getInvoker().sendMessage("You said: " + evt.getMessage());
        });

        System.out.println("Waiting for eserver events!");
        con.getServerHandler().addHandler(new ServerListener() {
            @Override
            public void onClientEnterView(ClientEnterViewEvent event) {
                LOG.log(Level.INFO, "ClientEnterViewEvent: {0}", event);
                event.getClient().sendMessage("Hello " + event.getClient().getNickname() + "!");
                event.getClient().getChannel().resolv().addListener((Future<Channel> channel) -> {
                    event.getClient().sendMessage("Welcome to channel " + channel.get().getName() + "!");
                });
            }

            @Override
            public void onClientLeaveView(ClientLeftViewEvent event) {
                LOG.log(Level.INFO, "ClientLeftViewEvent: {0}", event);
            }

            @Override
            public void onEditServer(ServerEditEvent event) {
                LOG.log(Level.INFO, "ServerEditEvent: {0}", event);
            }

        });

        Thread.sleep(100000);

        System.out.println("Closing...!");
        con.quit().sync().get();

    } finally {
        group.shutdownGracefully();
    }
}

From source file:nearenough.examples.NettyClient.java

License:Open Source License

public static void main(String[] args) throws InterruptedException {
    InetSocketAddress addr = new InetSocketAddress(INT08H_SERVER_HOST, INT08H_SERVER_PORT);

    System.out.printf("Sending request to %s\n", addr);

    // Below is Netty boilerplate for setting-up an event loop and registering a handler
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().group(nioEventLoopGroup).remoteAddress(addr)
            .channel(NioDatagramChannel.class).handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override// w  w  w  . j a va 2 s . c  om
                protected void initChannel(NioDatagramChannel ch) {
                    ch.pipeline().addLast(new ReadTimeoutHandler(5)).addLast(new RequestHandler(addr));
                }
            });

    ChannelFuture connectFuture = bootstrap.connect();
    connectFuture.addListener(future -> {
        if (!future.isSuccess()) {
            System.out.println("Connect fail:");
            System.out.println(future.cause().getMessage());
        }
    });

    connectFuture.channel().closeFuture().sync();
    nioEventLoopGroup.shutdownGracefully();
}

From source file:net.hasor.rsf.bootstrap.RsfBootstrap.java

License:Apache License

public RsfContext sync() throws Throwable {
    LoggerHelper.logInfo("initialize rsfBootstrap");
    if (this.rsfStart == null) {
        LoggerHelper.logInfo("create RsfStart.");
        this.rsfStart = new InnerRsfStart();
    }//from   w w  w  . jav a 2s  . c o m
    if (this.settings == null) {
        this.settings = new DefaultRsfSettings(new StandardContextSettings(DEFAULT_RSF_CONFIG));
        this.settings.refresh();
    }
    if (this.settings.getXmlNode("hasor.rsfConfig") == null) {
        throw new IOException("settings is not load.");
    }
    //
    //RsfContext
    LoggerHelper.logInfo("agent shutdown method on DefaultRsfContext.", DEFAULT_RSF_CONFIG);
    final DefaultRsfContext rsfContext = new DefaultRsfContext(this.settings) {
        public void shutdown() {
            LoggerHelper.logInfo("shutdown rsf.");
            super.shutdown();
            doShutdown();
        }
    };
    if (this.workMode == WorkMode.Customer) {
        return doBinder(rsfContext);
    }
    //
    //localAddress & bindSocket
    InetAddress localAddress = this.localAddress;
    if (localAddress == null) {
        localAddress = finalBindAddress(rsfContext);
    }
    int bindSocket = (this.bindSocket < 1) ? this.settings.getBindPort() : this.bindSocket;
    LoggerHelper.logInfo("bind to address = %s , port = %s.", localAddress, bindSocket);
    //Netty
    final URL hostAddress = URLUtils.toURL(localAddress.getHostAddress(), bindSocket);
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.settings.getNetworkListener(),
            new NameThreadFactory("RSF-Listen-%s"));
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, rsfContext.getLoopGroup());
    boot.channel(NioServerSocketChannel.class);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            Channel channel = ch.pipeline().channel();
            NetworkConnection.initConnection(hostAddress, channel);
            //
            ch.pipeline().addLast(new RSFCodec(), new RsfProviderHandler(rsfContext));
        }
    }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture future = boot.bind(localAddress, bindSocket);
    final Channel serverChannel = future.channel();
    LoggerHelper.logInfo("rsf Server started at :%s:%s", localAddress, bindSocket);
    //add
    this.shutdownHook = new Runnable() {
        public void run() {
            LoggerHelper.logInfo("shutdown rsf server.");
            bossGroup.shutdownGracefully();
            serverChannel.close();
        }
    };
    //
    return doBinder(rsfContext);
}

From source file:net.NettyEngine4.ServerServiceImpl.java

License:Apache License

/**
 *  run netty server/*from w w w .  ja  v a  2s  .  com*/
 *  NioEventLoopGroup used for NIO Selector based Channels
 *  two NioEventLoopGroup(AioEventLoopGroup) will be used. The first is
 *  used to handle the accept of new connections and the second will serve the IO of them.
 *  IoEventLoopGroupThread +1;
 *  DefaultEventExecutorGroup ?
 *
 *  bossExecutor:?SocketChannel
 *  workerExecutorSocketChannel?channel/
 *  executionLogicHandlerThread????
 *  AIO ?channelgroup?group?
 *  option() is for the NioServerSocketChannel that accepts incoming connections
 *  childOption() is for the Channels accepted by the parent ServerChannel,
 *  which is NioServerSocketChannel in this case.
 *
 *   ServerBootstrap ?? parent channel
 *   parent channel ? connections
 *  ? connection ? child channel ??
 */
@Override
public void run() throws Exception {
    NioEventLoopGroup EventLoopGroupLister = new NioEventLoopGroup(0x1,
            new PriorityThreadFactory("@+main_reactor+@", Thread.NORM_PRIORITY));
    NioEventLoopGroup IOEventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 1,
            new PriorityThreadFactory("@+sub_reactor+@", Thread.NORM_PRIORITY));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap.group(EventLoopGroupLister, IOEventLoopGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true) //??
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better
                .childOption(ChannelOption.SO_RCVBUF, 1048576).childOption(ChannelOption.SO_SNDBUF, 1048576)
                .childHandler(new ServerChannelInitializer());//used to serve the request for the {@link Channel}'s
        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress(Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort)).sync();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("server??:" + Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your server.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        EventLoopGroupLister.shutdownGracefully();
        IOEventLoopGroup.shutdownGracefully();
    }
}

From source file:nettyone.HttpRouterServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // This is an example router, it will be used at HttpRouterServerHandler.
    ////  w w  w . j av  a  2 s .  c  o m
    // For simplicity of this example, route targets are just simple strings.
    // But you can make them classes, and at HttpRouterServerHandler once you
    // get a target class, you can create an instance of it and dispatch the
    // request to the instance etc.
    Router<String> router = new Router<String>().GET("/", "Index page").notFound("404 Not Found");
    System.out.println(router);

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

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .channel(NioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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