我目前正在尝试使用netty创建一个聊天服务。我从一些源代码中获取了引用,我想实现一个简单的GUI,在服务器端,必须单击“发送”按钮,以便可以发送消息被发送回给客户。 我基本上尝试在我的 messageReceived channel 处理程序中实现 ActionListener 但遇到一些问题,因为我无法使用客户端的 channel 写回我的消息,因为非最终变量在使用时无法引用的问题是在以不同方法定义的内部类中。我希望得到一些建议来克服这个问题。感谢大家的帮助!
ServerHandler消息接收代码:
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)throws Exception {
System.out.println("Received message from client: " + e.getMessage());
String msgclient = (String) e.getMessage();
ta.append("[From Client]" + msgclient + "\n");
Channel c = e.getChannel();//can't declare it as final also,make no sense
bt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
if(a.getSource()==bt){
String serversentence=tf.getText();
ta.append("[Server]" + serversentence + "\n");
c.write(serversentence + "\n\r");
if (serversentence.toLowerCase().equals("shutdown"))
shutdown();
tf.setText(null);
}
}
});
}
最佳答案
您可以创建一个自定义 ActionListener 类,并在其构造函数中传递 channel 。
此外,您的代码将为收到的每条消息在按钮上注册一个新的 ActionListener。这真的是你想要的吗?如果它是聊天服务,那么在客户端连接时注册一次操作监听器是否更有意义?如果您要处理多个客户端,这可能也不合适。
关于java - 如何在netty聊天服务器端正确实现GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16958990/