gpt4 book ai didi

java - Netty WriteAndFlush 方法不起作用

转载 作者:行者123 更新时间:2023-11-30 06:15:23 31 4
gpt4 key购买 nike

看下面的代码:

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”结尾,才能flush。有了它们就不会冲洗。我不明白这是为什么,但无论如何。

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

最佳答案

您应该检查 writeAndFlush(...) 返回的 ChannelFuture 告诉您的内容。我敢打赌你会得到某种异常(exception)。

关于java - Netty WriteAndFlush 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28934777/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com