以编程方式关闭 netty

Posted

技术标签:

【中文标题】以编程方式关闭 netty【英文标题】:Shutdown netty programmatically 【发布时间】:2015-03-17 21:34:37 【问题描述】:

我正在使用 netty 4.0.24.Final。

我需要以编程方式启动/停止 netty 服务器。 在启动服务器时,线程在

处被阻塞

f.channel().closeFuture().sync()

请提供一些正确的提示。 下面是 Main 类调用的 EchoServer。 谢谢。

package nettytests;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioserverSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class EchoServer 

    private final int PORT = 8007;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public void start() throws Exception 
        // Configure the server.
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(1);
        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 
                     ch.pipeline().addLast(new EchoServerHandler());
                 
             );

            // Start the server.
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed. Thread gets blocked.
            f.channel().closeFuture().sync();
         finally 
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        
    

    public void stop()
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    



package nettytests;

public class Main 
    public static void main(String[] args) throws Exception 
        EchoServer server = new EchoServer();
        // start server
        server.start();

        // not called, because the thread is blocked above
        server.stop();
    

更新: 我通过以下方式更改了 EchoServer 类。这个想法是在一个新线程中启动服务器并保留到 EventLoopGroups 的链接。 这是正确的方法吗?

package nettytests;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Echoes back any received data from a client.
 */
public class EchoServer 

    private final int PORT = 8007;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public void start() throws Exception 
        new Thread(() -> 
            // Configure the server.
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup(1);
            Thread.currentThread().setName("ServerThread");
            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 
                                ch.pipeline().addLast(new EchoServerHandler());
                            
                        );

                // Start the server.
                ChannelFuture f = b.bind(PORT).sync();

                // Wait until the server socket is closed.
                f.channel().closeFuture().sync();
             catch (InterruptedException e) 
                e.printStackTrace();
             finally 
                // Shut down all event loops to terminate all threads.
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            
        ).start();
    

    public void stop() throws InterruptedException 
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    

【问题讨论】:

使用netty作为客户端时,使用f.channel().closeFuture().sync(),但是作为服务器使用时,使用f.channel().close().sync() 【参考方案1】:

一种方法是制作类似的东西:

// once having an event in your handler (EchoServerHandler)
// Close the current channel
ctx.channel().close();
// Then close the parent channel (the one attached to the bind)
ctx.channel().parent().close();

这样做会得到以下结果:

// Wait until the server socket is closed. Thread gets blocked.
f.channel().closeFuture().sync();

主体部分不需要额外的线程。 现在的问题是:什么样的事件?这取决于你......可能是回声处理程序中的一条消息,作为“关闭”,将被视为关闭的顺序,而不仅仅是“退出”,它将变成仅关闭客户端通道。可能是别的……

如果您不处理子通道的关闭(因此通过您的处理程序)而是通过另一个进程(例如寻找存在的停止文件),那么您需要一个额外的线程来等待此事件,然后直接制作一个channel.close(),其中频道将是父频道(来自f.channel()),例如...

还有许多其他解决方案。

【讨论】:

【参考方案2】:

我在关注官方教程时遇到了同样的问题。教程 有相同的模式:

f.channel().closeFuture().sync();
...
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();

也就是说,频道在组关闭之前被关闭。我把顺序改成了这样:

        bossGroup.shutdownGracefully().sync();
        workerGroup.shutdownGracefully().sync();
        f.channel().closeFuture().sync();

它奏效了。这导致了一个未锁定的服务器的粗略修改示例:

class Server

    private ChannelFuture future;
    private NioEventLoopGroup masterGroup;
    private NioEventLoopGroup workerGroup;
    Server(int networkPort)
    
        masterGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try
        
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(masterGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.option(ChannelOption.SO_BACKLOG,128);
            serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>()
            
                @Override
                protected void initChannel(SocketChannel ch)
                
                    ch.pipeline().addLast(new InboundHandler());
                
            ).validate();
            future = serverBootstrap.bind(networkPort).sync();
            System.out.println("Started server on "+networkPort);

        
        catch (Exception e)
        
            e.printStackTrace();
            shutdown();
        
    

    void shutdown()
    

        System.out.println("Stopping server");
        try
        
            masterGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
            future.channel().closeFuture().sync();
            System.out.println("Server stopped");
        
        catch (InterruptedException e)
        
            e.printStackTrace();
        
    

【讨论】:

【参考方案3】:

我刚刚关闭了事件循环组

 bossGroup.shutdownGracefully().sync();
 workerGroup.shutdownGracefully().sync();

而且效果很好,因为当我通过改造向代理服务器发送请求时,它说“连接失败”。

【讨论】:

以上是关于以编程方式关闭 netty的主要内容,如果未能解决你的问题,请参考以下文章

如何以编程方式关闭 Discord?

以编程方式关闭 iPhone?

以编程方式锁定或关闭屏幕

以编程方式关闭 Android 手机

如何以编程方式关闭/禁用 NFC?

如何以编程方式单击剑道树视图节点[关闭]