0

I'm learning to code in Java. I want to write simple chat with gui. So far my application works through command line. I'm interested to build up gui to client part. I have trouble connectiong gui to it. My question is do I have to write special class for gui and than construct such an object in client class and operate on it? In particular I have a problem with establishing communication between client and server via gui. My command line application code as for client part goes as follows. I would appreciate any advice on this matter.

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 4444);
            System.out.println("CLIENT: Server connected on port 4444");

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("CLIENT: IN and OUT streams opened. Starting sending data...");

            ClientInputThread thread = new ClientInputThread(socket);
            thread.start();

            String serverResponse;
            while ((serverResponse = in.readLine()) != null) {
                System.out.println("Server: " + serverResponse);
                if (serverResponse.equals("koniec")) {
                    break;
                }
            } 
            System.out.println("CLIENT: Ending server connection. Closing client streams and socket.");
            out.close();
            in.close();
            socket.close();
            System.exit(0);
        } 
        catch (UnknownHostException e) {
            System.err.println("CLIENT: Trying to connect to unknown host: " + e);
            System.exit(1);
        } 
        catch (Exception e) {
            System.err.println("CLIENT: Exception:  " + e);
            System.exit(1);
        }
    }
}

and

public class ClientInputThread extends Thread {
    private PrintWriter out;

    public ClientInputThread(Socket clientSocket) {
        try {
            out = new PrintWriter(clientSocket.getOutputStream(), true);
        } 
        catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void run() {
        try {    
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            String userInput="";    
            while (userInput != null) {
                userInput = console.readLine();
                out.println(userInput);
                out.flush();
                if (userInput.equals("koniec")) {
                    break;
                }
            }
            System.exit(0);
        } 
        catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
3
  • Connectivity shouldn't depend on whether it's a CLI or GUI. Commented Dec 24, 2012 at 13:57
  • I agree. But my main problem is how to direct server responses from console to, say, JTextField in gui and what puzzles me even more - where should I place my gui code - in separate class or in client class. Commented Dec 24, 2012 at 14:02
  • off topic.. Use properties to hold server settings such as port, url and others. Also use properties to hold exception messages. And use logger instead of System.out or System.err. Commented Dec 24, 2012 at 14:08

1 Answer 1

3

The usual practice is to separate your logic from the GUI as much as possible. I'd create a class (or a number of classes) that implements the send/receive message part (looks like you've done that already).

These classes should provide public methods to send/receive messages, and probably be able to register listeners and notify them of incoming messages.

Then write a GUI class(es), register it as a listener with your server class and update the text once a MessageReceived event has occured. Event handling basics can be found here and here is an example of creating and handling custom events.

Example

//an interface that will let your server work with its listeners
interface MessageListener {
    public void messageSent();
}


class Server {
    List<MessageListener> listeners = new ArrayList<MessageListener>();

    //method to register listeners to be notified of incoming messages
    public void addListener(MessageListener toAdd) {
        listeners.add(toAdd);
    }

    public void sendMessage() {
        //code your logic here
        System.out.println("Message sent");

        // Notify everybody that may be interested.
        for (MessageListener hl : listeners)
            hl.messageSent();
    }

}

class GuiImplementation implements MessageListener {
    @Override
    public void messageSent() {
         System.out.println(message);
    }
}

and the main class:

class Test {
    public static void main(String[] args) {
        Server server = new Initiater();
        GuiImplementation gui = new Responder();

        //register gui as a listener for incoming/outgoing messages
        server.addListener(gui);

        //this will trigger the gui method to process incoming message
        server.sendMessage(); 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.