我是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);
}