如何在netty框架中将服务器的响应发送回客户端

时间:2013-05-23 01:31:06

标签: netty

我是netty的新手,我尝试使用netty框架实现聊天服务器。客户端将从命令行向服务器发送一个msg。当通过键盘读入接收到msg时,服务器将相应地响应。然而,我从服务器的消息无法到达客户端。我已经对聊天服务器netty框架做了很多研究,我发现的所有开源代码基本上都是echo服务器。我不太清楚是什么问题。我附上了部分

来自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);

}

1 个答案:

答案 0 :(得分:2)

你在收到的消息处理器中创建了无限循环(for(;;)):你没有得到任何回复,因为Netty实际上不会发送任何数据(或用任何接收到的数据回叫你),直到你从收到的消息处理器返回。

看起来你从JBoss SecureChat客户端源代码(http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/securechat/SecureChatClient.html)中提取了你的例子:阅读http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/example/securechat/的其余源文件,以便更好地掌握如何执行此操作。< / p>