A comprehensive demonstration of Remote Procedure Call (RPC) implementations using both traditional RPC and modern gRPC in C++, C, and Go programming languages.
- Project Overview
- Understanding RPC Concepts
- Project Structure
- Prerequisites
- Quick Start
- Traditional RPC Implementation
- gRPC Implementation
- Code Walkthrough
- Running the Applications
- Understanding the Code
- Learning Outcomes
This project demonstrates distributed computing concepts through practical implementations of:
- Traditional RPC using Sun RPC (ONC-RPC) in C
- Modern gRPC using Protocol Buffers in C++ and Go
Both implementations provide arithmetic services (addition) to showcase client-server communication across networks.
RPC is a communication protocol that allows a program to execute procedures (functions) on a remote server as if they were local function calls. It abstracts the complexities of network communication from the developer.
-
Client-Server Architecture:
- Client makes procedure calls
- Server executes the procedures and returns results
-
Stub Functions:
- Client Stub: Marshals parameters and handles network communication
- Server Stub: Unmarshals parameters and calls actual server functions
-
Marshaling/Unmarshaling:
- Converting data structures to transmittable format (and vice versa)
- Handles data type conversion between different architectures
-
Interface Definition Language (IDL):
- Defines the contract between client and server
- Traditional RPC uses
.xfiles - gRPC uses Protocol Buffer
.protofiles
| Aspect | Traditional RPC | gRPC |
|---|---|---|
| Protocol | UDP/TCP | HTTP/2 |
| Data Format | XDR (External Data Representation) | Protocol Buffers |
| Language Support | Primarily C/C++ | Multi-language (50+ languages) |
| Performance | Fast, lightweight | Fast with additional features |
| Features | Basic RPC functionality | Streaming, authentication, load balancing |
| Modern Usage | Legacy systems | Modern microservices |
.
├── rpc_demo/ # Traditional RPC implementation (C)
│ ├── client/
│ │ ├── adder_client # Compiled client executable
│ │ ├── adder_client.c # Client implementation
│ │ └── build.sh # Client build script
│ ├── rpc/
│ │ ├── adder.x # RPC interface definition
│ │ ├── adder.h # Generated header file
│ │ ├── adder_clnt.c # Generated client stub
│ │ ├── adder_svc.c # Generated server stub
│ │ └── adder_xdr.c # Generated marshaling code
│ └── server/
│ ├── adder_server.c # Server implementation
│ ├── build.sh # Server build script
│ └── server # Compiled server executable
│
└── grpc_demo/ # gRPC implementations
├── cpp/ # C++ gRPC implementation
│ ├── client/
│ │ ├── client # Compiled client executable
│ │ ├── client.cpp # Client implementation
│ │ └── compile.sh # Client build script
│ ├── proto/
│ │ ├── add.proto # Protocol Buffer definition
│ │ ├── add.pb.cc # Generated Protocol Buffer code
│ │ ├── add.pb.h # Generated Protocol Buffer header
│ │ ├── add.grpc.pb.cc # Generated gRPC code
│ │ ├── add.grpc.pb.h # Generated gRPC header
│ │ └── build.sh # Proto build script
│ └── server/
│ ├── compile.sh # Server build script
│ ├── server # Compiled server executable
│ └── server.cpp # Server implementation
│
└── go/ # Go gRPC implementation
├── client/
│ ├── client # Compiled client executable
│ └── main.go # Client implementation
├── proto/
│ ├── add.proto # Protocol Buffer definition
│ ├── add.pb.go # Generated Protocol Buffer code
│ ├── add_grpc.pb.go # Generated gRPC code
│ └── build.sh # Proto build script
├── server/
│ ├── adder.go # Server service implementation
│ ├── main.go # Server main function
│ └── server # Compiled server executable
├── go.mod # Go module file
├── go.sum # Go dependencies checksum
└── README.md # Go-specific documentation
# Arch Linux
sudo pacman -S base-devel gcc rpcbind libtirpc rpcsvc-proto
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install libc6-dev gcc rpcbind libtirpc-dev
# CentOS/RHEL/Fedora
sudo yum install glibc-devel gcc rpcbind libtirpc-devel# Arch Linux
sudo pacman -S base-devel cmake pkgconf grpc protobuf
# Ubuntu/Debian
sudo apt-get install build-essential autoconf libtool pkg-config
sudo apt-get install libgrpc-dev libgrpc++-dev libprotobuf-dev protobuf-compiler-grpc
# Or build from source (recommended for latest version)
git clone --recurse-submodules -b v1.50.0 https://github.com/grpc/grpc
cd grpc
mkdir -p cmake/build && cd cmake/build
cmake -DgRPC_INSTALL=ON -DgRPC_BUILD_TESTS=OFF ../..
make -j 4
sudo make install# Install Go (version 1.18+)
# Arch Linux
sudo pacman -S go
# Ubuntu/Debian
sudo apt-get install golang-go
# Install Protocol Buffer compiler
# Arch Linux
sudo pacman -S protobuf
# Ubuntu/Debian
sudo apt-get install protobuf-compiler
# Install Go plugins for protobuf
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest# Navigate to RPC demo directory
cd rpc_demo
# Build and run server
cd server
chmod +x build.sh
./build.sh
./server# In a new terminal
cd rpc_demo/client
chmod +x build.sh
./build.sh
# Test integer addition
./adder_client -i localhost 10 20
# Test floating point addition
./adder_client -i localhost -f 10.5 20.7
# Test three number addition
./adder_client -i localhost 10 20 30cd grpc_demo/cpp
# Build protocol buffers
cd proto
chmod +x build.sh
./build.sh
# Build and run server
cd ../server
chmod +x compile.sh
./compile.sh
./server# In a new terminal
cd grpc_demo/cpp/client
chmod +x compile.sh
./compile.sh
./clientcd grpc_demo/go
# Build protocol buffers
cd proto
chmod +x build.sh
./build.sh
# Run server
cd ../server
go run *.go
# In a new terminal, run client
cd ../client
go run main.goThe RPC interface is defined using Sun RPC's Interface Definition Language:
program ADDER_PROG {
version ADDER_VERS {
int ADD(int_pair) = 1;
} = 1;
version ADDER_VERS_2 {
int ADD(int_pair) = 1;
float ADD_FLOAT(float_pair) = 2;
int ADD_THREE(int_triple) = 3;
} = 2;
} = 0x23451111;
struct int_pair {
int a;
int b;
};
struct float_pair {
float a;
float b;
};
struct int_triple {
int a;
int b;
int c;
};Key Elements:
- Program Number:
0x23451111- Unique identifier for this RPC service - Version Numbers: Support multiple versions of the same service
- Procedure Numbers: Unique identifiers for each remote procedure
- Data Structures: Define parameter and return types
The rpcgen tool generates several files from adder.x:
adder.h: Header file with function declarations and data structuresadder_clnt.c: Client-side stub functionsadder_svc.c: Server-side dispatcher and skeletonadder_xdr.c: Marshaling/unmarshaling functions (XDR format)
int *add_1_svc(int_pair *argp, struct svc_req *rqstp) {
static int result;
result = argp->a + argp->b;
return &result;
}Key Points:
- Functions must match the signature generated by
rpcgen - Return values are pointers to static variables
svc_reqstructure contains request metadata
clnt = clnt_create(ip, ADDER_PROG, ADDER_VERS_2, "udp");
result = add_2(&pair, clnt);Key Points:
- Creates a client handle for the remote service
- Calls remote procedures as if they were local functions
- Handles network communication transparently
syntax = "proto3";
package add_service;
service Adder {
rpc Add (AddRequest) returns (AddResponse);
}
service FloatAdder {
rpc Float_Add (FloatAddRequest) returns (FloatAddResponse);
}
message AddRequest {
int32 a = 1;
int32 b = 2;
}
message AddResponse {
int32 sum = 1;
}Key Features:
- Language Agnostic: Same
.protofile generates code for multiple languages - Strongly Typed: Explicit type definitions prevent runtime errors
- Versioning Support: Easy to evolve services over time
- Compact Serialization: Efficient binary format
class AdderServiceImpl final : public Adder::Service {
Status Add(ServerContext *context, const AddRequest *request, AddResponse *response) {
int sum = request->a() + request->b();
response->set_sum(sum);
return Status::OK;
}
};Key Features:
- Inherits from generated service base class
- Type-safe request/response handling
- Rich context information available
- Built-in status and error handling
func (s *adder_server) Add(ctx context.Context, req *pb.AddRequest) (*pb.AddResponse, error) {
sum := req.A + req.B
return &pb.AddResponse{Sum: sum}, nil
}Go-Specific Features:
- Idiomatic Go error handling
- Context-based cancellation and timeouts
- Automatic garbage collection
- Concurrent request handling with goroutines
-
Client Request:
// Client creates connection clnt = clnt_create("localhost", ADDER_PROG, ADDER_VERS_2, "udp"); // Prepare data int_pair pair = {10, 20}; // Call remote procedure result = add_2(&pair, clnt);
-
Network Communication:
- Client stub marshals parameters using XDR
- Sends UDP packet to server
- Server stub receives and unmarshals data
-
Server Processing:
int *add_2_svc(int_pair *argp, struct svc_req *rqstp) { static int result = argp->a + argp->b; return &result; }
-
Response Handling:
- Server marshals return value
- Sends response back to client
- Client stub unmarshals result
-
Client Request:
// Create channel and stub auto channel = grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()); auto stub = Adder::NewStub(channel); // Prepare request AddRequest request; request.set_a(10); request.set_b(20); // Make RPC call AddResponse response; ClientContext context; Status status = stub->Add(&context, request, &response);
-
HTTP/2 Communication:
- Protocol Buffer serialization
- HTTP/2 multiplexing and flow control
- Built-in compression and encryption options
-
Server Processing:
Status Add(ServerContext *context, const AddRequest *request, AddResponse *response) { response->set_sum(request->a() + request->b()); return Status::OK; }
cd rpc_demo/server
./build.sh
./serverThe server will start and listen for RPC calls. You should see output indicating the server is ready.
cd rpc_demo/client
./build.sh
# Basic addition (2 integers)
./adder_client -i localhost 15 25
# Output: Result 15 + 25 = 40
# Floating point addition
./adder_client -i localhost -f 10.5 20.7
# Output: Result 10.500000 + 20.700000 = 31.200000
# Three number addition
./adder_client -i localhost 5 10 15
# Output: Result 5 + 10 + 15 = 30
# Using remote server
./adder_client -i 192.168.1.100 10 20-i <ip_address>: Specify server IP address-f: Use floating-point arithmetic-h: Display help message
cd grpc_demo/cpp/proto
./build.sh
cd ../server
./compile.sh
./server -a 0.0.0.0 -p 50051Server options:
-a <address>: Bind address (default: 0.0.0.0)-p <port>: Port number (default: 50051)
cd grpc_demo/cpp/client
./compile.sh
./client -a localhost -p 50051Expected output:
Integer sum: 30
Float sum: 31
cd grpc_demo/go/proto
./build.sh
cd ../server
go run *.gocd grpc_demo/go/client
go run main.goExpected output:
Add response of 5 + 3 = 8
FloatAdd response of 5.5 + 3.2 = 8.7
-
Client Side:
Application → Client Stub → XDR Marshaling → Network -
Server Side:
Network → XDR Unmarshaling → Server Stub → Service Implementation
adder.x: Interface definition language fileadder_clnt.c: Generated client stub functionsadder_svc.c: Generated server dispatcheradder_xdr.c: Generated marshaling/unmarshaling codeadder_server.c: Your service implementationadder_client.c: Your client application
-
Client Side:
Application → gRPC Client → Protocol Buffer → HTTP/2 → Network -
Server Side:
Network → HTTP/2 → Protocol Buffer → gRPC Server → Service Implementation
protoc --cpp_out=. --grpc_out=. --plugin=protoc-gen-grpc=grpc_cpp_plugin add.protoGenerates:
add.pb.cc/h: Protocol Buffer message serializationadd.grpc.pb.cc/h: gRPC service stubs and skeletons
result = add_2(&pair, clnt);
if (!result) {
clnt_perror(clnt, "call failed");
// Handle error
}Status status = stub->Add(&context, request, &response);
if (status.ok()) {
// Success
} else {
std::cerr << "RPC failed: " << status.error_code()
<< ": " << status.error_message() << std::endl;
}- Pros: Lightweight, fast for simple operations
- Cons: Limited features, manual error handling
- Pros: Feature-rich, built-in load balancing, streaming
- Cons: Higher overhead for simple operations
- Uses UDP by default (fast but unreliable)
- Can use TCP for reliability
- No built-in security
- Uses HTTP/2 (multiplexing, flow control)
- Built-in TLS support
- Compression and authentication
After working through this project, you should understand:
- Remote Procedure Calls: How to make function calls across network boundaries
- Client-Server Architecture: Separation of concerns in distributed systems
- Interface Definition: Defining contracts between services
- Marshaling/Unmarshaling: Data serialization for network transmission
- Sun RPC Protocol: Understanding ONC-RPC mechanisms
- XDR Data Representation: Platform-independent data encoding
- Code Generation: How
rpcgencreates stub code - Network Programming: UDP/TCP socket programming abstractions
- Protocol Buffers: Efficient binary serialization
- HTTP/2 Protocol: Modern transport layer features
- Multi-language Support: Language-agnostic service definitions
- Advanced Features: Streaming, authentication, load balancing
- Service Design: How to design distributed services
- Error Handling: Robust error handling in distributed systems
- Build Systems: Managing dependencies and build processes
- Debugging: Troubleshooting network and RPC issues
- API Versioning: Managing service evolution
- Error Propagation: Proper error handling across network boundaries
- Performance Optimization: Choosing appropriate protocols and serialization
- Security Considerations: Authentication and encryption in distributed systems
# If rpcbind service is not running
# Arch Linux
sudo systemctl start rpcbind
sudo systemctl enable rpcbind
# Check if service is registered
rpcinfo -p localhost# If protobuf compiler is missing
# Arch Linux
sudo pacman -S protobuf
# Ubuntu/Debian
sudo apt-get install protobuf-compiler
# If gRPC libraries are not found
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH# Check if ports are listening
netstat -tlnp | grep :50051
ss -tlnp | grep :50051
# Test connectivity
telnet localhost 50051This comprehensive guide provides you with a solid foundation in both traditional RPC and modern gRPC technologies, demonstrating their practical applications and helping you understand the evolution of distributed computing protocols.