0% found this document useful (0 votes)
12 views9 pages

Lab Report Messenger

The document outlines the implementation of Remote Procedure Call (RPC) in a Java-based client-server architecture. It details the software requirements, theoretical background, and step-by-step code for basic and enhanced client-server communication, as well as RPC functionality. Key components include socket communication, message handling, and server-client interactions using Java's networking capabilities.

Uploaded by

jiniyasshah1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

Lab Report Messenger

The document outlines the implementation of Remote Procedure Call (RPC) in a Java-based client-server architecture. It details the software requirements, theoretical background, and step-by-step code for basic and enhanced client-server communication, as well as RPC functionality. Key components include socket communication, message handling, and server-client interactions using Java's networking capabilities.

Uploaded by

jiniyasshah1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Title: Implementation of RPC from basic Client-Server architecture

OBJECTIVE:
To establish a Remote Procedure Call for performing various tasks in a distributed
manner.

Software Requirements:
Java JDK
IDE: VS-CODE

Theory: t(101P
V-mirow
Remote Procedure Call (RPC): A Remote Procedure Call (RPC) is a protocol that
allows a program to execute a procedure on a different computer in a network as if it
were a local procedure call. It simplifies the process of communication between
distributed systems by abstracting the complexities of the network.

Java provides the j ava . net package to implement socket-based communication.


The key classes used are:

• Se rve rSocket: Allows the server to listen for incoming client connections.
• Socket: Facilitates communication between the client and server.
• PrintW rite r: Sends data to the socket as a stream of characters.
• Buffer edReader: Reads data from the socket as a stream of characters

Implementation:

1. Basic Client-Server Communication:


❑ The server listens on port 1234 and waits for a client connection. ❑
The client connects to the server and sends a message.
❑ The server receives the message and prints it.
2. Enhanced Client-Server Communication:
❑ The server keeps reading messages until the client sends an exit.
3. RPC Implementation:
❑ The server listens on port 5000.
❑ The client sends a request in the format method : a rgl : a rg2 : a rg3.
❑ The server processes the request and responds with the result.
Basic Client Server communication

Client:

1 import java.io.I0Exception;
2 import java.io.PrintWriter;
3 import java.net.Socket;
4
5 public class Client {
Run I Debug
6 public static void main(String args[]) throws IDException {
7 System.out.println(x:"Hello from client")
8 Socket socket = new Socket(host:"192.168. 1.76", port:1234);
9 PrintWriter out = new PrintWriterIsocket. getOutputStreaMO, autoFlush:true);
10 out.println(x:"Hello my name is Suraj");
11 out.close();
12 socket. close()
13 }
14 }

Server:

1 import java.io.BufferedReader;
2 import java.io.I0Exception;
3 import java.io.InputStreamReader;
4 import java.net.ServerSocket;
5 import java.net.Socket;
6
7 public class Server
8 public static void main(String args[]) throws I0Exception {
9 Systecout.println(x:"Hello from Server");
10 5erverSocket serverSocket = new ServerSocketIport:1234);
11 Socket clientSocket = serverSocket.accept();
12 BufferedReader in = new BufferedReader(new InputStreamReader(client5ocket.getInput5treami 0: :
13 String message = in.readLine();
14 System.out.println("Recieved: " + message);
15 in.close();
16 clientSocket.close();
17 serverSocket.close();
18
19 }

Output:

• xdzcO0Vold lab ta cd /Users/xdzcO/Desktop/lab /usr/bin/env /Lib • ,xdzcOgioid lab /usr/bin/env /LibrarynavanavaVirtualMachines/


rary/Java/3avaVirtualMachines/j&-20.jdis/ContentsMiome/bin/java - jdk-20.jdk/Contents1Mome/bin/java -XXN-StiowCodetletailsInException
XX:+ShowCodeDetailsInExceptionMessages -cp /Users/xdza/Library/A Messages -cp /Users/xdzcO/Library/ApplicationI Support/Code/User/
pplication\ Support/Code/User/workspaceSturage5dcff06680c160607 workspaceStorage5d0f8866e5c1806079a41286085e6c6/redhat.java/jdt
9a41286086e6c6/redhat.java/Idt ws/lab_d7426730/bin client ws/lab_d7426730/bin Server
Hello from client Hello from Server
xdzc00Void lab is Recieved; Hello my name is Suraj
The given code implements a basic client-server communication using Java sockets. Here's
how it works step-by-step:

Server Initialization:

a The Server class creates a Se rverSocket object that listens for incoming
connections on port 1234.

o
4‘,
The server waits for a client to connect using the accept ( ) method, which
blocks the execution until a client establishes a connection.

o Once a client connects, the server obtains a Socket object representing the
connection.

Client Initialization:
1■■
o The Client class attempts to establish a connection to the server by
creating a Socket object with the server's IP address (192.168.1.76) and port
(1234).

o Once the connection is established, the client can send data to the server
through the socket.

Data Transmission:

o In the client, a PrintWriter object is used to send the message "Hello


students" to the server.

o On the server side, a BufferedReader object reads the data sent by the
client using the readLine( ) method.

Data Reception and Display:

o The server receives the message and prints it using


System . out .println( "Received : " + message) ;.

- Closing Connections:

o After sending and receiving the message, both the client and server close
their respective sockets using the close( ) method to release resources and
terminate the connection.
Enhanced Client Server communication

Client:

1 package enhanced; 2
3 import java.io.I0Exception;
4 import java.io.PrintWriter;
5 import java.net.Socket;
6 import java.util.Scanner;
7
8 public class Client
RunIDebug
9 public static void main(String args[]) throws I0Exception {
10 System.out.println(x:"Hello from client");
11 Socket socket = new Socket(host:"localhost", port:1234);
12 PrintWriter out = new PrintWriter(socket.getOutputStream(), autoFlush:true);
13 Scanner scanner = new Scanner(System.in);// console read operation from keyboard
14 System.out.println(x:"Connected to server. Type messages (type 'exit' to quit):");
15 while (true) {
16 System.out.print(s:"Enter message: ");
17 String input = scanner.nextLine();
18 if ("exit".egualsIgnoreCase(input)) {
19 break;
20
21 out.println(input);
22
23 scanner.close(1;
24 out.close();
25 socket.close();
26 System.out.printlnix:"Disconnected from server.");
27
28 }

Server:

1 package enhanced; 2
3 import java.ia.BufferedReader;
4 import java.io.I0Exception;
5 import java.io.InputStreamReader;
6 import java.net.ServerSocket;
7 import java.net.Socket;
8
9 public class Server {
Run I Debug
10 public static void main(String argsp) throws I0Exception
11 System.out.println(x:"Hello from server");
12 ServerSocket serverSocket = new ServerSocket(port:1234);
13 System.out.printlnix:"Server is running... Waiting for client...');
14 Socket clientSocket = serverSocket.accept();
15 System.out.println(x:"Client connected!");
16 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
17 String line;
18 while ((line = in.readline()) != null) {
19 System.out.println("Received from client: " + line);
20 }
21 in.close();
22 clientSocket.close();
23 serverSocket.close));
24 System.out.println(x:"Client disconnected. Server shutting down.");
25 }
26 }

Output:

0 xdrapoid lab % cd /Users/xdxcD/Oesktop/lab ; /usr/bin/env /Lib ' mxdza@Void lab 4 cd /Users/xdza/Desktop/lab ; /usr/bin/env /Lib
rarynava/JaveVirtualMachines/jdk-29.jdk/Cootents/Home/bin/java - rary/Java/JavaVirtualtiachines/jdk-20.jdk/Contents/Mome/bin/java -
XX:+ShowCodeOetailsInExceptionMessages -cp /Users/xdza/Library/A XX:+ShowCodeDetailsInExceptionMessages -cp /Users/xdza/Library/A
pplicatiool SuppOrt/COde/USer/wOrkSpaCeStOrage/Sdcff886SeSC189607 pplitatiOn1 SuppOrt/COde/USer/wOrlopaCeStOrage/SdCff8868e5c160607
9a41286085e6c6/redhat.javaildt W lab_d7426736/bin enbanced.Clien 9a412861185e6c6/redbat.ibva/Ot ws/lah_d7426730/bin enhanced.Serve

Hello from client Hello from server


Connected to server. Type messages (type 'exit' to quit): Server is running... Waiting for client...
Enter message: Hi! My name is Suraj Adhikari Client connected!
Enter message: I can send multiple message Received from client: Hi! My name is Suraj Adhikari
Enter mesSage: exit Received from client: I can Send multiple message
Disconnected from server. Client disconnected. Server shutting down.

The given code implements enhanced client-server communication using Java sockets.
at-
Here's how it works step-by-step:

.■X
Server Initialization:

o The Server class creates a Se rverSocket object that listens for incoming
connections on port 1234.

o The server waits for a client to connect using the accept ( ) method, which
blocks the execution until a client establishes a connection.

o Once a client connects, the server obtains a Socket object representing the
connection.

o The server initializes both input and output streams to handle bidirectional
communication with the client.

Client Initialization:

a The Client class attempts to establish a connection to the server by


creating a Socket object with the server's IP address and port (1234).

o Once the connection is established, the client can send data to the server
through the socket and also read the server's responses.

Data Transmission: -11


The client sends a series of messages to the server using the PrintWriter
object]

a The server reads each message using a Buf fe redReade r and responds
back to the client with a confirmation message.

o The client can continue sending messages until it sends the exit command.

Data Reception and Display:

o The server receives the message and prints it to the console, and sends a
response back to the client.

o The client reads the server's response and prints it to its console.

Closing Connections:
cV
Once the client sends the exit command, the server closes the connection and
stops listening for further messages.

O The client also closes its socket and terminates its execution.
RPC Client Server communication

RPC Client:

1 package rpc;
2
3 import java.io.*;
4 import java.net.*;
5
6 public class RPCClient 1
Run I Debug
7 public static void main(String(1 ergs) throws I0Exception 1
8 Socket socket = new Socket(host:"192.168.1.76", port:50001;
9 PrintWriter out . new PrintWriter(socket.getputpUtStream(), autoFlush:true11
10 out.printlnIx:"mu1:5:3:2");
11 BufferedReader in = new BufferedReaderinew InputStreamReader(socket.getInputStream()));
12 String response = in.readline(61
13 System.out.printlm("Response from server: " + response};
14 socket.clOSe0;
15 in.close();
16 out.close(11
17
18 }
■14111111.

RPC Server:

1 package rpc;
2
3 import java.io.*;
4 import jampalet.*;
5

6 public class RPCServer


RuniDebug
7 public static void main(5tring(] ergs) 1
8 ServerSocket serverSocket = null;
9 try 1
10 serverSocket - new ServerSocket(port:50406;
11 System.out.println(x:"Server started. Listening on port 5000..."1;
12 while (true) I
13 Socket clientSocket = serverSOcket.aCcept();
14 try
15 BufferedReader in = new BufferedReader(new InputStreamReader(client5ocket.getInputStream(161;
16 PrintWriter out = new PrintWriter(client5ocket.getOutput5tream(6, autoFlush:true6)
17 String request = in.readLine();
18 String[] parts = request.splitIregex:":"6;
19 if (pafts.length == 4 && parts(01.equals(anobject:"mul"61 1
20 System.out.println("Server Running function :" parts[0]1;
21 int x = Integer.parseInt(parts[1]1:
22 int y = Integer.parseInt(parts[211;
23 int a = Integer.parseInt(parts[316;
24 int result = x * y * a;
25 out.println(resulht
26 else {
27 out.println(x:"Invalid request");
28
29 1 catch (IDException e1
30 System.err.println("Client handling error: " + e.getMessaget) ;
31 1 finally {
32 clientSocket.close0;
33
34 }
35 } catch (I0Exception e1 1
36 System.err.println("Server error: " + e.getMessaget)1;
37 6 finally {
38 if (serverSocket != null 64 iserver5ocket.isClos.edf11 {
39 try {
48 serverSocket.closelr;
41 System.out.println(x:"Server socket closed.");
42 1 catch (IOException e1
43 System.err.println{"Error closing server socket: e.geteessage(1::
44
45
46
47
48 }
Output:
xdrcO@Void lab % /usr/bin/env /tibraryilava/JavaVirtualklachines/' kelzakpold lab % iusr/bin/env /LIbrary/7ava/Javagirtualklachines/
jdk-20.jdk/Contents/Home/bin/java -XX:+5bowCodeDetallsInException jdk-20.jdk/Contents/Home/bin/jave -XX:*ShowtodeDetailsInException
Mensal Hesse
ges -cp /USerS/xdiC0/Library/OpplicationI Support/Code/User/works geS -cp /Users/xdza/Library/Applicationl Support/Code/User/wurks
paceStorage/5dcff8668e5c1B06079a41286085e6c6/redhat.java/jdt_ws/I paceStorage/5dcff8868e5c1806079a4128608Se6c6/redhat.java/Idt ws/I
ab_d7 ab_d7
426730/bin rpc.RPCClient 426730/bin rpc.RPCServer
Response from server: 30 Server started. Listening on port 5000...
{rodzcO@Void lab % 0 Server Running function :mul

The given code implements a simple Remote Procedure Call (RPC) mechanism using Java
sockets. Here's how it works step-by-step:

Server Initialization:

• The RPCServer class creates a ServerSocket object that listens for


incoming connections on port 5040.

• The line serverSocket = new Serve rSocket(5040) ; initializes the


server socket to listen for incoming client connections.

• The server enters an infinite loop and waits for client connections using the
accept ( ) method. This method blocks the server until a client establishes a
connection. Once a client connects, it returns a Socket object representing
the client connection. -low•P

• Inside the try block, the server initializes input and output streams using
BufferedReader for reading client requests and PrintWriter for sending
responses to the client.

2. Client Initialization:

• The RPCClient class attempts to connect to the server at IP address


192.168.1.76 on port 5040 using new Socket( "192 .168.1.76", 5040).

• This establishes a connection to the server.

• The client sends a request to the server using the PrintWriter object with
the message "nnul :5 : 3 : 2 "

• The request format is "mul : 5 :3 : 2", indicating that the client wants to
perform a multiplication operation with three parameters: 5, 3, and 2.

3. Data Processing and RPC Function Execution on Server:



• The server reads the client request using BufferedReader. The received
request is split into parts using the split ( " : " ) method.
• The request is expected to have four parts:

o parts[0]: The operation (e.g., "mul")

o parts[1], parts[2], parts[3]: The operands for the multiplication


operation

• The server checks if the request is valid and performs the multiplication
operation.

• If the request is valid, the server extracts the integers, performs the
multiplication, and sends the result back to the client. Otherwise, it sends an
"Invalid request" response.

4. Data Reception and Display on Client: r


• The client reads the server's response using Buf f e redRea de r.

• The response could be the multiplication result or an error message. 5.

Closing Connections:

• Once the client receives the response, it closes its streams and socket.

• The server closes the client socket after processing the request.

• If the server is terminated or encounters an error, it closes the server socket


in the finally block.

Conclusion:

• Successfully implemented basic client-server communication using Java


sockets in a distributed environment.
• Enhanced the server to handle continuous communication using loops.
• Implemented a simple RPC mechanism for performing multiplication using a
custom protocol.

You might also like