package chapter18;

/**
 * Title:        Chapter 18, "Networking"
 * Description:  Examples for Chapter 18
 * Copyright:    Copyright (c) 2000
 * Company:      Armstrong Atlantic State University
 * @author Y. Daniel Liang
 * @version 1.0
 */

// Server.java: The server accepts data from the client, processes it
// and returns the result back to the client

import java.io.*;
import java.net.*;

public class Server
{
  /**Main method*/
  public static void main(String[] args)
  {
    try
    {
      // Create a server socket
      ServerSocket serverSocket = new ServerSocket(8000);

      // Start listening for connections on the server socket
      Socket connectToClient = serverSocket.accept();

      // Create an input stream to get data from the client
      DataInputStream isFromClient = new DataInputStream(
        connectToClient.getInputStream());

      // Create an output stream to send data to the client
      DataOutputStream osToClient = new DataOutputStream(
        connectToClient.getOutputStream());

      // Continuously read from the client and process it,
      // and send result back to the client
      while (true)
      {
        // Read a string from the input stream
        double radius = isFromClient.readDouble();

        // Display radius on console
        System.out.println("radius received from client: " + radius);

        // Compute area
        double area = radius*radius*Math.PI;

        // Send the result to the client
        osToClient.writeDouble(area);
        osToClient.flush();

        // Print the result to the console
        System.out.println("Area found: " + area);
      }
    }
    catch(IOException ex)
    {
      System.err.println(ex);
    }
  }
}