0

i wan't to create a chat so i have server and client; server code:

            serverSocket = new ServerSocket(8080);
            mainSocket = serverSocket.accept();
            out = new PrintWriter(mainSocket.getOutputStream());
            in = new BufferedReader(new InputStreamReader(mainSocket.getInputStream()));
            gui = new JavaFXGUI();
            gui.setIn(in);
            gui.setOut(out);
            gui.run()

client code:

            clientSocket = new Socket("127.0.0.1", 8080);
            out = new PrintWriter(clientSocket.getOutputStream());
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            gui = new JavaFXGUI();
            gui.setIn(in);
            gui.setOut(out);
            gui.run()

JavaFXGUI :

public class JavaFXGUI extends Application{
    private BufferedReader in;
    private PrintWriter out;
    private ChatController chatController;

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader();
        URL xmlUrl = getClass().getResource("/GUI/scenes/mainScene.fxml");
        loader.setLocation(xmlUrl);
        System.out.println(in);
        chatController = new ChatController(out,in);

        loader.setController(chatController);
        Parent root = loader.load();

        primaryStage.setTitle("Chat");
        primaryStage.setWidth(800);
        primaryStage.setHeight(450);

        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
   
    public void run() {
        launch();
    }

    public void setIn(BufferedReader in) {
        this.in = in;
    }

    public void setOut(PrintWriter out) {
        this.out = out;
    }
}

so the problem is that in start method in and out parameters are null, why is this hapenning and how can i fix it. (i tried to pass in and out in constructor but it throws an error)

  • 4
    You should invert how this works, instead of having the client and server code create the GUI, have the GUI create the appropriate client and server code. See for example the [code in this answer](https://stackoverflow.com/a/70888362/1155209). You should never call `new` on a JavaFX application, the `launch()` method will generate an instance (of which there can only be one in the VM ever). – jewelsea Dec 13 '22 at 08:46

0 Answers0