You are on page 1of 5

Submitted by - Ritika Jaiswal, Roll No. 152191020, M.

Tech
S.E. First Year
Programming assignment1
Write a program to implement a calculator using Remote Procedure Call.
1. Server
CalculatorServer.java
import
java.net.*;
import
java.io.*;
public class CalculatorServer {
public static void main(String args[]) throws IOException {
/ Register service on port 1500
ServerSocket s = new
ServerSocket(1500);
Socket s1=s.accept(); // Wait and accept a connection
/ Get a communication stream associated with the socket
InputStream s1In = s1.getInputStream();
DataInputStream dis = new
DataInputStream(s1In); int num1 =
(dis.readInt());
int num2 = (dis.readInt());
String operation =
(dis.readUTF()); //String st =
new String (dis.readUTF()); int
ans = 0;
if (operation.equals("add")
== true){ ans = num1 +
num2;
}
else if
(operation.equals("sub")
){ ans = num1 - num2;
}
else if

(operation.equals("m
ul")){ ans = num1 *
num2;

else if
(operation.equals("di
v")){ ans = num1 /
num2;

}
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream
(s1out); dos.writeUTF("Answer from server : " + ans); //
Send a string to client // Close the connection, but not
the server socket
dos.close();

s1out.close();
s1.close();

To compile the CalculatorServer.java, the


command is

javac Calculator.java

2. Client
CalculatorClient.java
import java.net.*;
import
java.util.Scanner;
import java.io.*;
public class CalculatorClient {
public static void main(String args[]) throws
IOException {
/ Open your connection to a server, at
port
1500
Socket
s1
=
new
Socket("localhost",1500);
/ Get an input file handle from the socket and
read the input Scanner scanln = new
Scanner(System.in);
System.out.println("Enter
number1: "); int num1 =
scanln.nextInt();
System.out.println("Enter
number2: "); int num2 =
scanln.nextInt();
System.out.println("Operation: ");
String operation = scanln.next();
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new
DataOutputStream (s1out);
dos.writeInt(num1); //send to server
dos.writeInt(num2); //send to server
dos.writeUTF(operation);
InputStream s1In = s1.getInputStream();
DataInputStream dis = new
DataInputStream(s1In); String st = new
String (dis.readUTF());
System.out.println("" + st);
// When done, just close the connection
and exit dis.close();
s1In.close();
s1.close();
}

To compile CalculatorClient.java, type the following


command

javac CalculatorClient.java

3. Execution
1. First run the Server using the following command

java CalculatorServer

2. In another instance of command prompt, run the Client using the


following command

jjvj
jjljuljtor
jljjnt
jutput