I am attempting to write a server / client socket program and a client GUI using JavaFX. My issue that i am facing is where the GUI and socket connection doesn't run independently of each other meaning when i run my client program the GUI is shown and the socket connection doesn't occur. Then after closing the GUI window the socket connection will initialize as it should've originally. Also not greatly experienced with java in general and javafx/socket programming, just trying to learn.
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();
}
}
I have tried doing small steps, like getting the socket connection working properly by itself then trying to implement the javafx GUI alongside it. I still couldn't get it running the GUI and the socket connection together. I would assume the the JavaFX GUI is somehow on a loop that stops itself closing as soon as it starts which then holds the socket program from starting until the GUI has finished running. So only when the GUI is closed, then the socket program starts.