Netty WriteAndFlush方法不起作用

时间:2015-03-09 03:20:59

标签: java network-programming netty

看哪以下代码:

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 + "\r\n");

        }

        // 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修改而添加的

            ch.writeAndFlush("hi");
在while循环之前

。服务器上的输出不读取该行。我无法理解为什么会这样,对我而言,ch.writeandflush方法本身几乎不会在循环之外工作。

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

解决方案:所有writeandflush语句必须以" \ r \ n"结尾。为了冲洗。他们没有冲洗。我不明白为什么会这样,无论如何。

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

2 个答案:

答案 0 :(得分:3)

解决方案:所有writeandflush语句必须以“\ r \ n”结尾才能刷新。他们没有冲洗。我不明白为什么会这样,无论如何。

代码解决方案:ch.writeAndFlush(“hi \ r \ n”);

答案 1 :(得分:2)

您应该检查writeAndFlush(...)返回的ChannelFuture告诉您的内容。我打赌你得到某种例外。