创建一个服务和客户端,完成随意输入3个整数,求取三个整数中的最大值。Cpp格式
时间: 2024-05-02 13:18:45 浏览: 65
输入三位数找最大值.cpp
服务端代码:
```cpp
#include <iostream>
#include <string>
#include <grpcpp/grpcpp.h>
#include "max.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using max::MaxRequest;
using max::MaxReply;
using max::MaxService;
class MaxServiceImpl final : public MaxService::Service {
Status GetMax(ServerContext* context, const MaxRequest* request,
MaxReply* reply) override {
int a = request->a();
int b = request->b();
int c = request->c();
int max = std::max(a, std::max(b, c));
reply->set_max(max);
return Status::OK;
}
};
void RunServer() {
std::string server_address("0.0.0.0:50051");
MaxServiceImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main(int argc, char** argv) {
RunServer();
return 0;
}
```
客户端代码:
```cpp
#include <iostream>
#include <memory>
#include <grpcpp/grpcpp.h>
#include "max.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using max::MaxRequest;
using max::MaxReply;
using max::MaxService;
class MaxClient {
public:
MaxClient(std::shared_ptr<Channel> channel)
: stub_(MaxService::NewStub(channel)) {}
int GetMax(int a, int b, int c) {
MaxRequest request;
request.set_a(a);
request.set_b(b);
request.set_c(c);
MaxReply reply;
ClientContext context;
Status status = stub_->GetMax(&context, request, &reply);
if (status.ok()) {
return reply.max();
} else {
std::cout << "RPC failed: " << status.error_code() << ": "
<< status.error_message() << std::endl;
return -1;
}
}
private:
std::unique_ptr<MaxService::Stub> stub_;
};
int main(int argc, char** argv) {
MaxClient client(grpc::CreateChannel("localhost:50051",
grpc::InsecureChannelCredentials()));
int a, b, c;
std::cout << "Please input three integers: ";
std::cin >> a >> b >> c;
int max = client.GetMax(a, b, c);
std::cout << "The max integer is: " << max << std::endl;
return 0;
}
```
阅读全文