看下面的代码:

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”);

最佳答案

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

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

07-27 21:23
查看更多