Here is an example of a gRPC server written in C programming language:

#include <stdio.h>
#include <stdbool.h>
#include <grpc/grpc.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include "example.grpc.pb.h"

using example::HelloRequest;
using example::HelloReply;
using example::Greeter;

class GreeterServiceImpl final : public Greeter::Service {
 public:
  grpc::Status SayHello(grpc::ServerContext* context, const HelloRequest* request,
                         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");
  GreeterServiceImpl service;

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

  std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
  printf("Server listening on %s\n", server_address.c_str());
  server->Wait();
}

int main(int argc, char** argv) {
  RunServer();
  return 0;
}

In this example, we define a gRPC server that listens on port 50051 and provides a SayHello method that takes a HelloRequest message and returns a HelloReply message with a personalized greeting. We use the grpc::ServerBuilder class to construct the server and register the GreeterServiceImpl class as the implementation of the Greeter service. Finally, we start the server and wait for incoming requests using the server->Wait() method.

write code gRPC server by C programing language

原文地址: https://www.cveoy.top/t/topic/0AG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录