I'm trying to create a multithreaded server, connecting to it through a client works fine, but the GUI is frozen. Probably since it is constantly listening for incoming connections it is stuck in a while loop. So, do i need to create a thread for the multithreaded server (which itself will be creating threads) or how would i go about fixing this?
MultiThreadedServer:
public class MultiThreadServer{
public static final int PORT = 2000;
//function below is called by the GUI.
public void startServer() throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Server socket: " + s);
System.out.println("Server listening...");
try { while(true) {
// Blocks until a connection occurs:
Socket socket = s.accept();
System.out.println("Connection accepted.");
System.out.println("The new socket: " + socket);
try {
ClientThread t = new ClientThread(socket);
System.out.println("New thread started.");
System.out.println("The new thread: " + t);
}
catch(IOException e) {
System.out.println("===Socket Closed===");
socket.close();
}
}
}
finally { System.out.println("===ServerSocket Closed==="); s.close(); }
}
}
}
ServerGUI:
public class ServerGUI extends Application implements Initializable{
@FXML private MenuItem startConn;
@Override
public void start(Stage stage) throws Exception {
try {
Parent root = FXMLLoader.load(getClass().getResource("ServerGUI.fxml"));
stage.setScene(new Scene(root));
stage.show();
} catch (IOException ex) {
ex.printStackTrace();
System.exit(0);
}
}
public static void main(String[] args) {
launch(args);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
startConn.setOnAction(e -> {
try {
MultiThreadServer mts = new MultiThreadServer();
mts.startServer();
System.out.println("Starting Server...");
} catch (IOException e1) {
e1.printStackTrace();
}
});
}
}