Java Programs[Important]
- WRITE A JAVA
PROGRAM that implements a simple client/server application. The client sends
data to a server. The server receives the data, uses it to produce a result and
then sends the result back to the client. The client displays the result on the
console. For ex: The data sent from the client is the radius of a circle and
the result produced by the server is the area of the circle.
-
- Program :
-
- // Server Program
import .io.*;
- import .net.*; import .util.*;
-
- public class
Server
- {
- public void static main (String args [ ] )
- {
- try
- {
- // create a server
socket ServerSocket s = new ServerSocket(8000);
-
- // start
listening for connections on srver socket
- Socket
connectToClient = s.accept();
-
- // create a
buffered reader stream to get data from client BufferedReader isFromClient =
new BufferedReader(new InputStreamReader (connectToClient.getInputStream()));
-
- // create a
buffer reader to send result to client PrintWriter osToClient = new
PrintWriter(connectToClient.getOutputStream(), true);
-
- // continuously
read from client, process, send back while (true) { // read a line and create
string tokenizer StringTokenizer st = new
StringTokenizer(isFromClient.readLine());
-
- //convert string
to double double radius = new Double(st.nextToken()).doubleValue();
-
- System.out.println(“Radius
received from client: “ + radius);
-
- // comput area
double area = radius * radius *Math.PI;
-
- // send result to
client osToClient.println(area);
-
- // print result
on console System.out.println(“Area found: “ +area); }
- }
- catch (IOException e)
- {
- System.err.println(e);
- }
- }
- }
- // Client Program
import .io.*;
- import .net.*; import .util.*;
-
- public class
Client
- {
- public void static main (String args [ ] )
- {
- try
- {
- // create a socket
to connect to server Socket connectToServer = new Socket(“local host”, 8000);
-
- // create a
buffered input stream to get result from server BufferedReader isFromServer =
new BufferedReader(new InputStreamReader (connectToServer.getInputStream()));
-
- // create a
buffer output stream to send data to server PrintWriter osToServer = new
PrintWriter(connectToClient.getOutputStream(), true);
-
- // continuously
send radius and get area
- while (true)
- {
- Scanner input=new Scanner(System.in);
- System.out.print(“Please
enter a radius: “);
- double radius =input.nextDouble();
-
- // display radius
on console osToServer.println(radius);
-
- // get area from
server StringTokenizer st = new StringTokenizer(isFromServer.readLine());
-
- // convert string
to double Double area = new Double(st.nextToken()).doubleValue();
-
- // print result on
console System.out.println(“Area received from the server is: “ +area);
- }
- }
- catch (IOException e)
- {
- System.err.println(e);
- }
- }
- }