0

我是netty的新手,我尝试使用netty框架实现聊天服务器。客户端将从命令行向服务器发送一条消息。当通过从键盘读取接收到一条消息时,服务器将相应地响应。但是,我的来自服务器的消息无法到达客户端。我对聊天服务器 netty 框架进行了大量研究,我能找到的所有开源代码基本上都是回显服务器。我不太确定是什么问题。我附上了部分

从 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();


 }

从 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);

}

4

1 回答 1

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/上的源文件,以便更好地掌握如何执行此操作。

于 2013-05-23T01:36:46.970 回答