Write client and server programs in which a server program accepts the length and breadth of a rectangle from the client program, computes area, sends the computed area to the client program, and displays it by client program.
Java client and server programs
Client Side Program : Java client and server programs
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author Achyut1324
*/
public class Client2 {
public static void main(String[] args) throws IOException {
final String HOST = "127.0.0.1";
final int PORT = 12345;
System.out.println("Client started.");
try (
Socket socket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner in = new Scanner(socket.getInputStream());
Scanner s = new Scanner(System.in);
) {
while (true) {
System.out.print("Input: Lenghth and Breadth ");
String length = s.nextLine();
String breath = s.nextLine();
out.println(length);
out.println(breath);
System.out.println("Echoed from server: " + in.nextLine());
}
}
}
}
Server Program :Java client and server programs
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author Achyut1324
*/
public class Server2 {
public static void main(String[] args) throws IOException {
final int PORT = 12345;
System.out.println("Server started.");
System.out.println("Listening to client...");
try (
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
Scanner in = new Scanner(clientSocket.getInputStream());
) {
while (true) {
String length = in.nextLine();
String breadth = in.nextLine();
if (length.equalsIgnoreCase("exit")) break;
System.out.println("Length Received from client: " + length);
System.out.println("Breadth Received from client: " + breadth);
double l = Double.valueOf(length);
double b = Double.valueOf(breadth);
double area = l*b ;
out.println(area);
}
}
System.out.println("Server stopped");
}
}
Output of the Program :
Client side
run:
Client started.
Input: Lenghth and Breadth 4
7
Echoed from server: 28.0
Input: Lenghth and Breadth
Server Side
run:
Server started.
Listening to client…
Length Received from client: 4
Breadth Received from client: 7