本文介绍了Netty WriteAndFlush 方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的代码:

public final class SecureChatClient {

static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new NetworkInitializer(sslCtx));

        // 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));
        //does not work
        ch.writeAndFlush("hi");
        while (true) {
            String line = in.readLine();
         if (line == null) {
            break;
            //(goes to if writefuture !=null)
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "
");

        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        // The connection is closed automatically on shutdown.
        group.shutdownGracefully();
    }
}}

该代码是从 netty 的 SecureChatClient 类 http://netty 修改的.io/wiki/user-guide-for-4.x.html 添加的行

That code was modified from netty's SecureChatClient Class http://netty.io/wiki/user-guide-for-4.x.html with the added in line

            ch.writeAndFlush("hi");

在while循环之前.服务器上的输出不会读取该行.我不明白为什么会这样,对我来说,ch.writeandflush 方法本身似乎在循环之外不起作用.

before the while loop. The output on the server does not read that line. I can't understand why that is, and to me it almost seems like the ch.writeandflush method itself doesn't work outside of a loop.

如果我不应该在循环之外使用 ch.writeandlfush,有没有更好的方法在启动时向服务器发送消息?

If im not supposed to use ch.writeandlfush outside of a loop, is there any better way to send a message to a server on startup?

解决方案:所有 writeandflush 语句必须以"结尾才能刷新.没有,他们不冲洗.我不明白为什么会这样.

Solution: all writeandflush statements must end with "" in order to flush. With out that they dont flush. I don't understand why that is but whatever.

代码解决方案:ch.writeAndFlush("hi");

Code solution: ch.writeAndFlush("hi");

推荐答案

解决方案:所有 writeandflush 语句必须以"结尾才能刷新.没有,他们不冲洗.我不明白为什么会这样.

Solution: all writeandflush statements must end with "" in order to flush. With out that they dont flush. I don't understand why that is but whatever.

代码解决方案:ch.writeAndFlush("hi");

Code solution: ch.writeAndFlush("hi");

这篇关于Netty WriteAndFlush 方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 15:05