Friday, 3 March 2017

Chapter 31 Exercise 2, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

31.2 (BMI server) Write a server for a client. The client sends the weight and
height for a person to the server (see Figure  31.18a). The server computes
BMI (Body Mass Index) and sends back to the client a string that reports the
BMI (see Figure 31.18b). See Section 3.8 for computing BMI. Name the client
Exercise31_02Client and the server Exercise31_02Server.

import java.io.*;
import java.net.*;
import java.util.*;
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 Exercise02s extends Application {
  // Text area for displaying contents
  private TextArea ta = new TextArea();

  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    ta.setWrapText(true);
   
    // Create a scene and place it in the stage
    Scene scene = new Scene(new ScrollPane(ta), 200, 200);
    primaryStage.setTitle("Exercise31_02Server"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
    
    new Thread(() -> connectToClient()).start();
  }  
  
  public void connectToClient() {
    try {
      // Create a server socket
      ServerSocket serverSocket = new ServerSocket(8000);
      Platform.runLater(() ->
        ta.appendText("Exercise31_02Server started at " + new Date() + '\n'));

      Socket connectToClient = serverSocket.accept();

      // Display the client number
      Platform.runLater( () -> {ta.appendText("Connected to a client " +
        " at " + new Date() + '\n');});

      // Create data input and output streams
      DataInputStream isFromClient = new DataInputStream(
        connectToClient.getInputStream());
      DataOutputStream osToClient = new DataOutputStream(
        connectToClient.getOutputStream());

      // Continuously serve the client
      while (true) {
        // Receive weight from the client
        double weight = isFromClient.readDouble();

        // Receive height from the client
        double height = isFromClient.readDouble();

        // Compute BMI
        BMI bmi = new BMI("", weight, height);
        String report = "BMI is " + bmi.getBMI() + ". " + bmi.getStatus();

        // Send results back to the client
        osToClient.writeUTF(report);

        Platform.runLater( () -> {
          ta.appendText("Weight: " + weight + "\nHeight: " + height + "\n");
          ta.appendText(report + '\n');
        });
      }
    }
    catch(IOException e) {
      System.err.println(e);
    }
  }
  
  /**
   * 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);
  }
  public class BMI {
  private String name;
  private int age;
  private double weight; // in pounds
  private double height; // in inches
  public static final double KILOGRAMS_PER_POUND = 0.45359237; 
  public static final double METERS_PER_INCH = 0.0254;  
  
  public BMI(String name, int age, double weight, double height) {
    this.name = name;
    this.age = age;
    this.weight = weight;
    this.height = height;
  }
  
  public BMI(String name, double weight, double height) {
    this(name, 20, weight, height);
  }
  
  public double getBMI() {
    double bmi = weight * KILOGRAMS_PER_POUND / 
      ((height * METERS_PER_INCH) * (height * METERS_PER_INCH));
    return Math.round(bmi * 100) / 100.0;
  }
  
  public String getStatus() {
    double bmi = getBMI();
    if (bmi < 18.5)
      return "Underweight";
    else if (bmi < 25)
      return "Normal";
    else if (bmi < 30)
      return "Overweight";
    else
      return "Obese";
  }
  
  public String getName() {
    return name;
  }
  
  public int getAge() {
    return age;
  }
  
  public double getWeight() {
    return weight;
  }
  
  public double getHeight() {
    return height;
  }
}

}

import java.io.*;
import java.net.*;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
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.scene.layout.GridPane;
import javafx.stage.Stage;

public class Exercise02c extends Application {
  // Text field for receiving radius
  private TextField tfWeight = new TextField();
  private TextField tfHeight = new TextField();
  private Button btSubmit= new Button("Submit");

  // Text area to display contents
  private TextArea ta = new TextArea();

  // IO streams
  DataOutputStream osToServer;
  DataInputStream isFromServer;
  
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    ta.setWrapText(true);
   
    GridPane gridPane = new GridPane();
    gridPane.add(new Label("Weight in pounds"), 0, 0);
    gridPane.add(new Label("Height in inches"), 0, 1);
    gridPane.add(tfWeight, 1, 0);
    gridPane.add(tfHeight, 1, 1);
    gridPane.add(btSubmit, 2, 1);
    
    tfWeight.setAlignment(Pos.BASELINE_RIGHT);
    tfHeight.setAlignment(Pos.BASELINE_RIGHT);
    
    tfWeight.setPrefColumnCount(5);
    tfHeight.setPrefColumnCount(5);
            
    BorderPane pane = new BorderPane();
    pane.setCenter(new ScrollPane(ta));
    pane.setTop(gridPane);
    
    // Create a scene and place it in the stage
    Scene scene = new Scene(pane, 200, 200);
    primaryStage.setTitle("Exercise31_02Client"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
    
    btSubmit.setOnAction(e -> connectToServer());
    
    try {
      // Create a socket to connect to the server
      Socket connectToServer = new Socket("localhost", 8000);
      //Socket connectToServer = new Socket("130.254.204.36", 8000);
      //Socket connectToServer = new Socket(
      //  "drake.Armstrong.edu", 8000);

      // Create an input stream to receive data from the server
      isFromServer = new DataInputStream(
        connectToServer.getInputStream());

      // Create an output stream to send data to the server
      osToServer =
        new DataOutputStream(connectToServer.getOutputStream());
    }
    catch (IOException ex) {
      ta.appendText(ex.toString() + '\n');
    }
  }
    
  public void connectToServer() {
    try {
      // Get the weight from the text field
      double weight = Double.parseDouble(tfWeight.getText().trim());

      // Get the height from the text field
      double height = Double.parseDouble(tfHeight.getText());

      // Send the weight to the server
      osToServer.writeDouble(weight);

      // Send the height to the server
      osToServer.writeDouble(height);

      osToServer.flush();

      // Get BMI from the server
     String report = isFromServer.readUTF();

      ta.appendText("Weight: " + weight + "\nHeight: " + height + "\n");
      ta.appendText(report + '\n');
    }
    catch (IOException ex) {
      System.err.println(ex);
    }
  }
  
  /**
   * 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);
  }
}

No comments :

Post a Comment