#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
// 假设我们有一个简单的 RPC 服务,定义在 .proto 文件中
// 这里是一个示例的 proto 文件内容:
/*
service HelloWorldService {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
*/
// 生成的代码会包含这些类
class HelloWorldService final : public helloworld::HelloWorldService::Service {
public:
grpc::Status SayHello(grpc::ServerContext* context, const helloworld::HelloRequest* request, helloworld::HelloReply* reply) override {
std::string prefix("Hello ");
reply->set_message(prefix + request->name());
return grpc::Status::OK;
}
};
void RunServer() {
std::string server_address("0.0.0.0:50051");
HelloWorldService service;
grpc::EnableDefaultHealthCheckService(true);
grpc::ServerBuilder builder;
// Listen on the given address without any authentication mechanism.
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
// Register "service" as the instance through which we'll communicate with
// clients. In this case it corresponds to an *synchronous* service.
builder.RegisterService(&service);
// Finally assemble the server.
std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
// Wait for the server to shutdown. Note that some other thread must be
// responsible for shutting down the server for this call to ever return.
server->Wait();
}
int main(int argc, char** argv) {
RunServer();
return 0;
}
gRPC 框架:这段代码使用了 gRPC 框架来实现远程过程调用(RPC)。gRPC 是一个高性能、开源和通用的 RPC 框架,支持多种编程语言。
Protobuf 定义:在注释部分展示了如何定义 .proto 文件中的服务和消息。这个文件需要通过 protoc 编译器生成 C++ 代码。
服务实现:HelloWorldService 类实现了 SayHello 方法,该方法接收一个 HelloRequest 并返回一个 HelloReply。在这个例子中,它只是简单地将传入的名字加上前缀 "Hello " 并返回。
服务器启动:RunServer 函数配置并启动了一个 gRPC 服务器,监听在 0.0.0.0:50051 地址上,并注册了 HelloWorldService 实例。
主函数:main 函数调用了 RunServer 来启动服务器。
要运行此代码,你需要安装 gRPC 和 Protobuf 的 C++ 库,并确保你的项目正确链接了这些库。
上一篇:c++静态变量
下一篇:c++求字符串长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站