Client / Server Application

Aim: 
To 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.

Description: 
Socket programming is a low level way to establish a connection between client and server. Socket is a point of connection where client and server exchange information using a port number. Read input from keyboard and send that information from client to server using Data Output Stream. In turn server read data from Buffered Reader and performs computation on the data and sends the output to client using Print Stream class. The client read the information from Buffered Reader and displays it on the monitor. The streams are available in java.io package.

Program:
//server
import java.io.*;
import java.net.*;
class Server
{
public static void main(String ar[])throws Exception
{ ServerSocket ss=new ServerSocket(7777);
Socket s=ss.accept();
System.out.println("Connection Established...");
BufferedReader br = new BufferedReader(new InputStreamReader
(s.getInputStream()));
int n=Integer.parseInt(br.readLine());
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(3.14*n*n);
s.close();
ss.close();
}
}
//client
import java.io.*;
import java.net.*;
class Client
{
public static void main(String ar[])throws Exception
{
Socket s=new Socket("localhost",7777);
System.out.println("Enter the radius of the circle ");
BufferedReader kb =new BufferedReader(new InputStreamReader (
System.in));
int n = Integer.parseInt(kb.readLine());
DataOutputStream ds=new DataOutputStream (s.getOutputStream());
ds.writeBytes( n + "\n");
BufferedReader br = new BufferedReader(new InputStreamReader
(s.getInputStream()));
System.out.println("Area of the circle from server:"+ br.readLine());
}
}