Reputation: 146
Behold The following code:
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();
}
}}
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");
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.
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?
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.
Code solution: ch.writeAndFlush("hi\r\n");
Upvotes: 2
Views: 6657
Reputation: 146
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.
Code solution: ch.writeAndFlush("hi\r\n");
Upvotes: 3
Reputation: 23557
You should check what the ChannelFuture that is returned by writeAndFlush(...) tells you. I bet you get some sort of exception.
Upvotes: 3