Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MultiThreaded Quadratic Equation Solver Server
- // A.C. Silvestri
- // 4/29/17
- // CSC-112 Intermediate Java Programming
- // silvestri@stcc.edu
- // HW 10
- package server;
- import java.io.*;
- import java.util.*;
- import java.net.*;
- import java.text.SimpleDateFormat;
- public class QuadraticThreadedServer {
- private static final int PORTNUMBER = 5009;
- private static void pStr(String p) {
- System.out.println(p);
- }
- private void runServer() {
- ServerSocket server;
- Socket connection;
- try {
- pStr("Creating Server Socket " + PORTNUMBER + " . . . ");
- server = new ServerSocket(PORTNUMBER);
- pStr("SUCCESS!!!");
- while (true) {
- pStr("Waiting for connection.");
- connection = server.accept();
- pStr("Done");
- CalculateQuadraticThread t = new CalculateQuadraticThread(connection);
- t.start();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private class CalculateQuadraticThread extends Thread {
- private Socket connection;
- public CalculateQuadraticThread(Socket x) {
- connection = x;
- }
- public void run() {
- pStr("");
- pStr("Communicating with " + connection.getInetAddress() + " " + connection.getPort());
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- Date date = new Date();
- pStr("Time: " + dateFormat.format(date));
- double a, b, c;
- double r1 = 0, r2 = 0;
- int status;
- String errmsg = "";
- try (
- Scanner input = new Scanner(connection.getInputStream());
- PrintWriter output = new PrintWriter(connection.getOutputStream());
- ) {
- a = Double.parseDouble(input.nextLine());
- b = Double.parseDouble(input.nextLine());
- c = Double.parseDouble(input.nextLine());
- if (a == 0) {
- status = -1;
- errmsg = "Not a Quadratic Equation";
- } else {
- double discrim = b * b - 4 * a * c;
- if (discrim < 0) {
- status = 0;
- } else if (discrim == 0) {
- status = 1;
- r1 = -b / (2 * a);
- } else {
- status = 2;
- r1 = (-b + Math.sqrt(discrim)) / (2 * a);
- r2 = (-b - Math.sqrt(discrim)) / (2 * a);
- }
- }
- output.println(status);
- output.flush();
- if (status == -1) {
- output.println(errmsg);
- output.flush();
- } else if (status == 1) {
- output.println(r1);
- output.flush();
- } else if (status == 2) {
- output.println(r1);
- output.flush();
- output.println(r2);
- output.flush();
- }
- }
- catch (Exception e) {
- pStr("Error! " + e.getMessage());
- }
- finally {
- try {
- connection.close();
- } catch (Exception e) {
- }
- }
- }
- }
- public static void main(String args[]) {
- QuadraticThreadedServer s = new QuadraticThreadedServer();
- s.runServer();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement