我正试图使用JavaFX编写一个服务器/客户端套接字程序和一个客户端GUI。我的问题是GUI和套接字连接无法独立运行,这意味着当我运行客户端程序时,GUI会显示,但套接字连接不会发生。然后在关闭GUI窗口后,套接字连接将初始化,就像原本应该的那样。 对于Java和JavaFX/套接字编程并没有太多经验,只是在尝试学习。
import java.io.*;
import java.lang.*;
import java.net.Socket;
public class ClientSocket {
public Socket socket;
public BufferedReader bufferedReader;
public BufferedWriter bufferedWriter;
public ClientSocket(Socket socket) {
try {
this.socket = socket;
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
closeConnection(socket, bufferedReader, bufferedWriter);
}
}
public static void startConnection() {
try {
Socket socket = new Socket(Configuration.serverAddress, Configuration.serverPort);
System.out.println("Client: Connected to server on " + Configuration.serverAddress +
" " + Configuration.serverPort + ".");
} catch (IOException e) {
System.out.println("Client: Error connecting to server on " + Configuration.serverAddress +
" " + Configuration.serverPort + ".");
}
}
public static void closeConnection(Socket socket, BufferedReader bufferedReader, BufferedWriter bufferedWriter) {
try {
if (socket != null) {
socket.close();
System.out.println("Client: Socket connection has been closed to " + Configuration.serverAddress +
" " + Configuration.serverPort + ".");
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
}catch(IOException e){
}
}
}
import javafx.application.Application;
import javafx.stage.Stage;
public class ClientWindow extends Application{
public void start(Stage gameWindow) {
gameWindow.show();
}
}
import javafx.application.Application;
public class Client {
public static void main(String[] args) {
Application.launch(ClientWindow.class, args);
ClientSocket.startConnection();
}
}
我尝试了一些小步骤,比如让套接字连接单独正常工作,然后再试着在其旁边实现JavaFX GUI。但我仍然无法同时运行GUI和套接字连接。我猜测JavaFX GUI可能在一个循环中,导致它启动后不会立即关闭,这就使得套接字程序无法开始运行,直到GUI完成运行。所以只有在GUI关闭后,套接字程序才会启动。