Reputation: 51
i am new to netty and i trying to implement a chat server using netty framework.The client will send an msg from command line to the server.The server will response accordingly when an msg is received by reading in from the keyboard.However, my msg from server is unable to reach client.I have done alot of research on chat server netty framework and all the open source code that i could found are basically echo server.I not too sure what is the issue.I attached the part
messageReceived from clientHandler :
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)throws IOException {
System.out.println("Received message from server: " + e.getMessage());
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
ChannelFuture lastWriteFuture = null;
for(;;){
String sentence;
sentence = inFromUser.readLine();
if (sentence.toLowerCase().equals("shutdown")) {
channel.getCloseFuture().awaitUninterruptibly();
break;
}
lastWriteFuture =channel.write(sentence+ "\r\n");
}
//Wait until all messages are flushed before closing the channel.
if (lastWriteFuture != null) {
lastWriteFuture.awaitUninterruptibly();
}
channel.close().awaitUninterruptibly();
}
messageReceived from serverHandler:
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)throws IOException {
System.out.println("Received message from client: " + e.getMessage());
String msgclient = (String) e.getMessage();
if (msgclient.toLowerCase().equals("bye")) {
e.getChannel().close().awaitUninterruptibly();
shutdown();
}
BufferedReader infromserver =new BufferedReader( new InputStreamReader(System.in));
String serversentence;
serversentence = infromserver.readLine();
System.out.println(serversentence);
Channel c=e.getChannel();
ChannelFuture f =Channels.future(e.getChannel());
ChannelEvent responseEvent = new DownstreamMessageEvent(c, f, serversentence ,c.getRemoteAddress());
ctx.sendDownstream(responseEvent);
System.out.println(channels.size());
System.out.println(responseEvent);
}
Upvotes: 0
Views: 2298
Reputation: 64700
You're creating infinite loops (for(;;)
) inside the message received handlers: you're not getting any response back because Netty will not actually send any data (or call you back with any received data) until you return from the message received handler.
It looks like you took your example from the JBoss SecureChat client source (http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/securechat/SecureChatClient.html): read through the rest of the source files at http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/securechat/ to get a good grasp of how to do this.
Upvotes: 2