Created
March 17, 2023 05:53
-
-
Save mougua/f0b5cfa912edaee2c90e6e66f731636b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author: ChatGPT | |
#include <iostream> | |
#include <memory> | |
#include <string> | |
#include <thread> | |
#include <grpcpp/grpcpp.h> | |
#include "example.grpc.pb.h" | |
using grpc::Channel; | |
using grpc::ClientAsyncResponseReader; | |
using grpc::ClientContext; | |
using grpc::CompletionQueue; | |
using grpc::Status; | |
using example::ExampleRequest; | |
using example::ExampleResponse; | |
using example::ExampleService; | |
using std::chrono::system_clock; | |
class ExampleClient { | |
public: | |
explicit ExampleClient(std::shared_ptr<Channel> channel) | |
: stub_(ExampleService::NewStub(channel)) {} | |
void Run() { | |
CompletionQueue cq; | |
std::thread thread(&ExampleClient::HandleResponses, this, &cq); | |
ClientContext context; | |
std::shared_ptr<ClientAsyncResponseReader<ExampleResponse>> response_reader( | |
stub_->AsyncExampleMethod(&context, &cq, (void*)1)); | |
ExampleRequest request; | |
request.set_message("Hello, server!"); | |
response_reader->Finish(&response_, &status_, (void*)1); | |
while (!finished_) { | |
std::cout << "Sending request..." << std::endl; | |
context.TryCancel(); | |
response_reader = stub_->AsyncExampleMethod(&context, &cq, (void*)1); | |
response_reader->Write(request, (void*)1); | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
} | |
cq.Shutdown(); | |
thread.join(); | |
} | |
private: | |
void HandleResponses(CompletionQueue* cq) { | |
void* tag; | |
bool ok; | |
while (cq->Next(&tag, &ok)) { | |
if (!ok) { | |
std::cout << "RPC failed" << std::endl; | |
break; | |
} | |
if (tag == (void*)1) { | |
if (status_.ok()) { | |
std::cout << "Received response: " << response_.message() << std::endl; | |
} else { | |
std::cout << "RPC failed with status code " << status_.error_code() << std::endl; | |
finished_ = true; | |
} | |
} | |
} | |
} | |
std::unique_ptr<ExampleService::Stub> stub_; | |
ExampleResponse response_; | |
Status status_; | |
bool finished_ = false; | |
}; | |
int main(int argc, char** argv) { | |
grpc::init(); | |
std::shared_ptr<Channel> channel = grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()); | |
ExampleClient client(channel); | |
client.Run(); | |
grpc::shutdown(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment