How do I launch the client class from the server(main) class

Viewed 100

In my assignment we are supposed to modify the code so the Main class launches a server and then launch a client where we input a number and it is sent to the server and then it is determined if it is prime or not and the result is returned to the client. Both run and interact fine but I have to run both individually. How can I run the Main(server) program first and then have it automatically launch the client?

package application;//Server code starts here
    
import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class Main extends Application {
    @Override // Override the start method in the Application class
      public void start(Stage primaryStage) {
        // Text area for displaying contents
        TextArea ta = new TextArea();
        // Create a scene and place it in the stage
        Scene scene = new Scene(new ScrollPane(ta), 450, 200);
        primaryStage.setTitle("Server"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
        
        new Thread( () -> {
          try {
            // Create a server socket
            ServerSocket serverSocket = new ServerSocket(8000);
            Platform.runLater(() ->
              ta.appendText("Server started at " + new Date() + '\n'));
      
            // Listen for a connection request
            Socket socket = serverSocket.accept();
      
            // Create data input and output streams
            DataInputStream inputFromClient = new DataInputStream(
              socket.getInputStream());
            DataOutputStream outputToClient = new DataOutputStream(
              socket.getOutputStream());
      
            while (true) {
              // Receive input number from the client
              int inputNumber = inputFromClient.readInt();
              System.out.println("Input number received is:" + inputNumber + "\n");
              ta.appendText("The number recieved is:"+inputNumber+"\n  Sending result...\n");
              int flag = 1, n;
              n = inputNumber/2;
      
              // Check for prime
              if(inputNumber==0||inputNumber==1)
              {  
                flag=0;      
              }
              else
                  {  
                   for(int i=2;i<=n;i++)
                   {      
                    if(inputNumber%i==0)
                    {            
                     flag=0;
                     break;
                    }      
                   }    
                  }  
       
              // Send result back to the client
              outputToClient.writeInt(flag);
      
             /* Platform.runLater(() -> {
                ta.appendText("Radius received from client: " 
                  + radius + '\n');
                ta.appendText("Area is: " + area + '\n'); 
              });*/
            }
          }
          catch(IOException ex) {
            ex.printStackTrace();
          }
        }).start();
      }
      /**
       * The main method is only needed for the IDE with limited
       * JavaFX support. Not needed for running from the command line.
       */
      public static void main(String[] args) {
        launch(args);
      }
}

package application; //Client code starts here

import java.io.*;
import java.net.*;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Client extends Application {
  // IO streams
  DataOutputStream toServer = null;
  DataInputStream fromServer = null;
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    // Panel p to hold the label and text field
    BorderPane paneForTextField = new BorderPane();
    paneForTextField.setPadding(new Insets(5, 5, 5, 5)); 
    paneForTextField.setStyle("-fx-border-color: green");
    paneForTextField.setLeft(new Label("Enter an integer: "));
    
    TextField tf = new TextField();
    tf.setAlignment(Pos.BOTTOM_RIGHT);
    paneForTextField.setCenter(tf);
    
    BorderPane mainPane = new BorderPane();
    // Text area to display contents
    TextArea ta = new TextArea();
    mainPane.setCenter(new ScrollPane(ta));
    mainPane.setTop(paneForTextField);
    
    // Create a scene and place it in the stage
    Scene scene = new Scene(mainPane, 450, 200);
    primaryStage.setTitle("Client"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
    
    tf.setOnAction(e -> {
      try {
        // Get the radius from the text field
        int inputNumber = Integer.parseInt(tf.getText().trim());
  
        // Send the radius to the server
        toServer.writeInt(inputNumber);
        toServer.flush();
  
        // Get area from the server
        int flag = fromServer.readInt();
  
        // Display to the text area
        ta.appendText("The number input is " + inputNumber + "\n");
        
        if(flag==1)
        {
        ta.appendText(inputNumber + " is a prime number\n");
        }
        else
        {
        ta.appendText(inputNumber + " is not a prime number\n");
        }
      }
      catch (IOException ex) {
        System.err.println(ex);
      }
    });
  
    try {
      // Create a socket to connect to the server
      Socket socket = new Socket("localhost", 8000);
      // Socket socket = new Socket("130.254.204.36", 8000);
      // Socket socket = new Socket("drake.Armstrong.edu", 8000);
      // Create an input stream to receive data from the server
      fromServer = new DataInputStream(socket.getInputStream());
      // Create an output stream to send data to the server
      toServer = new DataOutputStream(socket.getOutputStream());
    }
    catch (IOException ex) {
      ta.appendText(ex.toString() + '\n');
    }
  }
  /**
   * The main method is only needed for the IDE with limited
   * JavaFX support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
}
1 Answers

Create a new client and start it with a new stage.

Client client = new Client();
Stage clientStage = new Stage();
clientStage.initOwner(primaryStage);
client.start(clientStage);

Do this at the end of the start(Stage primaryStage) method for the Main application and it will immediately create a new client window on startup.

Unless you additionally need to start the client separately from the command line in a completely different process, there is no need for it to also have a main method or subclass the Application class.

Related