почему sync () не работает в netty для ChannelFuture - PullRequest
0 голосов
/ 21 ноября 2019

Я изучаю Netty, я не совсем понимаю метод синхронизации для ChannelFuture, вот мои примеры:

public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Usage: " + EchoServer.class.getSimpleName() + " <port>");
            return;
        }

        int port = Integer.parseInt(args[0]);

        new EchoServer(port).start();
    }

    public void start() throws Exception {
        // final EchoServerHandler serverHandler = new EchoServerHandler();
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // ch.pipeline().addLast(serverHandler);
                }
            });

            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}



public class EchoClient {
    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // ch.pipeline().addLast(new EchoClientHandler());
                }
            });


            ChannelFuture f = b.connect().sync().addListener(future -> {

                   if(future.isSuccess()) {

                       System.out.println(port + " bind success");

                   } else{

                       System.err.println(port + " bind fail");

                   }

               });

            System.out.println("aaa");

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

    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.err.println("Usage: " + EchoClient.class.getSimpleName() + " <host> <port>");
            return;
        }

        String host = args[0];
        int port = Integer.parseInt(args[1]);

        new EchoClient(host, port).start();
    }
}

У меня вопрос, что бы я ни удалил sync () в EchoClient.class дляChannelFuture f = b.connect (). Sync () или нет, результат всегда: aaa 8811 успех связывания

, по моему мнению, если я добавлю sync (), результат должен быть: 8811 успех связывания aaa

, так как основной поток будет ожидать подключения к каналу,

, если я удалю синхронизацию (), результат должен быть: aaa 8811 успех связывания

как соединение() асинхронный

почему я ошибаюсь?

1 Ответ

0 голосов
/ 27 ноября 2019

sync() разблокируется, как только операция завершится, а затем EventLoop уведомит всех подключенных слушателей к ChannelFuture. Поскольку ваш основной поток и поток EventLoop различаются, существует высокая вероятность того, что вы увидите System.out.println(...) в основном потоке перед тем, что в ChannelFutureListener

...