user2408159
user2408159

Reputation: 51

How to properly implement GUI in netty chat server side

i currently trying to create a chat service using netty.I took my references from some source code and i would like to implement a simple GUI where at the server side, a button "send" has to be clicked such that messages can be send back to client. I basically trying to implement an ActionListener in my messageReceived channelhandler but i encounter some problem as i would not be able to use the channel from client to write back my messages due to the issue that a non-final variable can't be reference when it is in an inner class defined in a different method.I hope for some advice to overcome this problem.Thks everyone for your kind assistance!

ServerHandler messageReceived code:

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

  });

}           

Upvotes: 0

Views: 510

Answers (1)

johnstlr
johnstlr

Reputation: 1431

You could create a custom ActionListener class which is passed the channel in its constructor.

Also your code will register a new ActionListener on the button for every message received. Is that really what you want? If it's a chat service would it make more sense to register the action listener once when the client client connects? This may not be suitable either if you're handling multiple clients.

Upvotes: 1

Related Questions