我正在学习用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);
}
}
}