Advanced Java Programming - Old Questions
12. What is a socket? Write client and server programs in which a server program accepts a radius of a circle from the client program. Computes area, sends the computed area to the client program, and displays it by client program.[1+4]
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
Program
// Server Program
import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[]) throws IOException
{
ServerSocket ss=new ServerSocket(1064);
System.out.println("Waiting for Client Request");
Socket s=ss.accept();
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("Received radius");
double r=Double.valueOf(str);
double area=3.14*r*r;
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(String.valueOf(area));
br.close();
ps.close();
s.close();
ss.close();
}
}