cpp-grpc-server

implement a grpc server

define proto file

request a json string respoinse a json string

syntax = "proto3";

package apiService;

service apiService {
rpc apiTrans(Request) returns (Response) {}
}

message Request {
string value = 1;
}

message Response {
string value = 1;
}

generate cpp file

protoc --cpp_out=. rpc_api.proto

source code

class ApiService : public apiService::apiService::Service
{
// 构造、析构
public:

// 接口实现
public:
virtual ::grpc::Status apiTrans(::grpc::ServerContext* context,
const ::apiService::Request* request, ::apiService::Response* response) override
{
string strJson = request->value();
OutputDebugStringA(strJson.c_str());

response->set_value(strJson);
return grpc::Status::OK;
}
};

void rpcServer()
{
std::string server_address("0.0.0.0:52061");

ApiService service;

grpc::ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);

std::unique_ptr<grpc::Server> server(builder.BuildAndStart());

std::cout << "Server listening on " << server_address << std::endl;

server->Wait();
}