以编程方式关闭Netty

17

我正在使用 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();
    }
}

1
当你将Netty用作客户端时,请使用f.channel().closeFuture().sync(),但是当你将其用作服务器时,应该使用f.channel().close().sync() - Terran
3个回答

16

一种方法是制作类似于:

// 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();

主要部分不需要额外的线程。

现在的问题是: 什么样的事件呢?这由您决定...... 可能是“shutdown”作为回声处理程序中的一条消息,该消息将被视为关闭命令,而不仅仅是“quit”,后者只会关闭客户端通道。也可能是其他内容...

如果您不通过子通道处理关闭(例如通过查找是否存在停止文件来处理),则需要一个额外的线程来等待此事件,然后直接进行channel.close() ,其中通道将是父通道(来自f.channel())等等......

还有许多其他解决方案。


0

我刚刚关闭了事件循环组

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

它很好地工作,因为当我使用Retrofit发送请求到我的代理服务器时,它会显示“连接失败”。


0

我在跟随官方教程进行学习时遇到了同样的问题。教程都有相同的模式:

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();
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接