问题描述
看哪以下代码:
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 Class 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");
。服务器上的输出不读取该行。我无法理解为什么会这样,对我而言,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语句必须以\\结尾\\ r \\ n为了冲洗。他们没有冲洗。我不明白为什么会这样但是无论如何。
Solution: all writeandflush statements must end with "\r\n" in order to flush. With out that they dont flush. I don't understand why that is but whatever.
代码解决方案:ch.writeAndFlush(hi\r\ n);
Code solution: ch.writeAndFlush("hi\r\n");
推荐答案
解决方案:所有writeandflush语句必须以\\\\ n结尾才能刷新。他们没有冲洗。我不明白为什么会这样但是无论如何。
Solution: all writeandflush statements must end with "\r\n" in order to flush. With out that they dont flush. I don't understand why that is but whatever.
代码解决方案:ch.writeAndFlush(hi\r\ n);
Code solution: ch.writeAndFlush("hi\r\n");
这篇关于Netty WriteAndFlush方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!