Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Name: Lu Liu
- * Date: 4/29/2016
- * Course Number: CSC-112
- * Course Name: Intermediate Topics in Java Programming
- * Email: lliu0001@student.stcc.edu
- *
- * Assignment: HW # 16
- * Programe Description:
- * Quadratic Equation Calculator Web Server
- */
- 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 CalculatorServer 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(5007);
- 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 data from the client
- try {
- double a = inputFromClient.readDouble();
- double b = inputFromClient.readDouble();
- double c = inputFromClient.readDouble();
- double d = b * b - 4 * a * c;
- int status = 0;
- double root1, root2;
- // Compute the root
- if (d == 0) {
- status = 1;
- } else if (d > 0) {
- status = 2;
- } else if (d < 0) {
- status = 0;
- }
- // Send data back to the client
- outputToClient.writeInt(status);
- switch (status) {
- case 1:
- outputToClient.writeDouble(-b / (2 * a));
- break;
- case 2:
- outputToClient.writeDouble((-b + Math.sqrt(d)) / (2 * a));
- outputToClient.writeDouble((-b - Math.sqrt(d)) / (2 * a));
- break;
- }
- } catch (Exception e) {
- outputToClient.writeInt(0);
- }
- }
- } 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement