【问题标题】:How to properly implement GUI in netty chat server side如何在 netty 聊天服务器端正确实现 GUI
【发布时间】:2013-06-10 16:07:43
【问题描述】:

我目前正在尝试使用 netty 创建一个聊天服务。我从一些源代码中获取了我的引用,我想实现一个简单的 GUI,在服务器端,必须单击一个按钮“发送”以便消息可以发回给客户。 我基本上试图在我的 messageReceived 通道处理程序中实现一个 ActionListener 但我遇到了一些问题,因为我无法使用来自客户端的通道写回我的消息,因为当它时非最终变量不能被引用的问题是在一个用不同方法定义的内部类中。我希望有一些建议来解决这个问题。感谢大家的帮助!

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

  });

}           

【问题讨论】:

    标签: java tcp connection netty


    【解决方案1】:

    您可以创建一个自定义 ActionListener 类,该类在其构造函数中传递通道。

    您的代码还将为收到的每条消息在按钮上注册一个新的 ActionListener。这真的是你想要的吗?如果它是一个聊天服务,在客户端连接时注册一次动作监听器会更有意义吗?如果您要处理多个客户,这可能也不适合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      相关资源
      最近更新 更多