Project Ds
Project Ds
What is RPC?
Remote Procedure Call (RPC) is a communication protocol that allows a program to call procedures or
methods on another program or computer over a network. It enables distributed computing by allowing
different systems to communicate with each other seamlessly.
Stubs: Client and server stubs handle the communication. The client stub converts the request
into a network message, and the server stub receives this message and invokes the actual
procedure.
Response: The server stub sends the result back to the client stub, which then returns it to the
client.
Create a .proto file to define the RPC service and message structure using Protocol Buffers.
text
syntax = "proto3";
service Calculator {
}
message AddRequest {
int32 num1 = 1;
int32 num2 = 2;
message AddResponse {
int32 result = 1;
rpc Add (AddRequest) returns (AddResponse);: Declares a method named Add that takes an
AddRequest message and returns an AddResponse message.
After defining your service in a .proto file, use the protoc compiler to generate client and server code in
your preferred language.
Example Command:
bash
Generated Files:
Server Implementation:
Create a server class that implements the service methods defined in your .proto file.
python
import grpc
import calculator_pb2
import calculator_pb2_grpc
class CalculatorService(calculator_pb2_grpc.CalculatorServicer):
return calculator_pb2.AddResponse(result=result)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
calculator_pb2_grpc.add_CalculatorServicer_to_server(CalculatorService(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()
if __name__ == "__main__":
serve()
Add Method: Handles the Add RPC call by adding two numbers.
Client Implementation:
python
import grpc
import calculator_pb2
import calculator_pb2_grpc
def run():
stub = calculator_pb2_grpc.CalculatorStub(channel)
print(f"Result: {response.result}")
if __name__ == "__main__":
run()
Add Call: Sends a request to the server and prints the result.
Execute the client script to send a request to the server and display the response.
This detailed explanation covers the process of setting up a basic RPC application using gRPC, from
defining the service to running the client and server.