0

我正在学习用Java编写代码。我想用gui写简单的聊天。到目前为止,我的应用程序通过命令行工作。我有兴趣为客户端部分建立 gui。我无法将 gui 连接到它。我的问题是我是否必须为 gui 编写特殊类,然后在客户端类中构造这样一个对象并对其进行操作?特别是我在通过 gui 在客户端和服务器之间建立通信时遇到问题。我的客户端部分的命令行应用程序代码如下。我将不胜感激有关此事的任何建议。

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

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

1 回答 1

3

通常的做法是尽可能将您的逻辑与 GUI 分开。我会创建一个类(或多个类)来实现发送/接收消息部分(看起来你已经这样做了)。

这些类应该提供公共方法来发送/接收消息,并且可能能够注册侦听器并通知它们传入的消息。

然后编写一个 GUI 类,将其注册为服务器类的侦听器,并在MessageReceived事件发生后更新文本。可以在此处找到事件处理基础知识,这里是创建和处理自定义事件的示例。

例子

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

和主要课程:

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(); 
    }
}
于 2012-12-24T14:03:23.530 回答