如何在netty聊天服务器端正确实现gui

lstz6jyr  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(385)

我正在尝试使用netty创建一个聊天服务,我引用了一些源代码,我想实现一个简单的gui,在服务器端,必须单击一个按钮“send”,这样就可以将消息发送回客户端。我基本上是想在我的messagereceived channelhandler中实现actionlistener,但遇到了一些问题,因为当一个非final变量在另一个方法中定义的内部类中时,它不能被引用,所以我无法使用客户端的通道来写回我的消息。我希望得到一些建议克服这个问题。谢谢大家的帮助!
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);
        }
    }

  });

}
dba5bblo

dba5bblo1#

您可以创建一个自定义actionlistener类,该类在其构造函数中传递给通道。
此外,您的代码将为收到的每条消息在按钮上注册一个新的actionlistener。那真的是你想要的吗?如果是聊天服务,那么在客户端连接时注册一次操作侦听器是否更有意义?如果您处理多个客户机,这可能也不合适。

相关问题