| 50 | |
| 51 | |
| 52 | int main(int argc, char* argv[]) { |
| 53 | // Parse gflags. We recommend you to use gflags as well. |
| 54 | GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true); |
| 55 | |
| 56 | // A Channel represents a communication line to a Server. Notice that |
| 57 | // Channel is thread-safe and can be shared by all threads in your program. |
| 58 | brpc::Channel channel; |
| 59 | |
| 60 | // Initialize the channel, NULL means using default options. |
| 61 | brpc::ChannelOptions options; |
| 62 | options.protocol = FLAGS_protocol; |
| 63 | options.connection_type = FLAGS_connection_type; |
| 64 | options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/; |
| 65 | options.max_retry = FLAGS_max_retry; |
| 66 | if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) { |
| 67 | LOG(ERROR) << "Fail to initialize channel"; |
| 68 | return -1; |
| 69 | } |
| 70 | |
| 71 | // Normally, you should not call a Channel directly, but instead construct |
| 72 | // a stub Service wrapping it. stub can be shared by all threads as well. |
| 73 | example::EchoService_Stub stub(&channel); |
| 74 | |
| 75 | // Send a request and wait for the response every 1 second. |
| 76 | int log_id = 0; |
| 77 | while (!brpc::IsAskedToQuit()) { |
| 78 | // Since we are sending asynchronous RPC (`done' is not NULL), |
| 79 | // these objects MUST remain valid until `done' is called. |
| 80 | // As a result, we allocate these objects on heap |
| 81 | example::EchoResponse* response = new example::EchoResponse(); |
| 82 | brpc::Controller* cntl = new brpc::Controller(); |
| 83 | |
| 84 | // Notice that you don't have to new request, which can be modified |
| 85 | // or destroyed just after stub.Echo is called. |
| 86 | example::EchoRequest request; |
| 87 | request.set_message("hello world"); |
| 88 | |
| 89 | cntl->set_log_id(log_id ++); // set by user |
| 90 | if (FLAGS_send_attachment) { |
| 91 | // Set attachment which is wired to network directly instead of |
| 92 | // being serialized into protobuf messages. |
| 93 | cntl->request_attachment().append("foo"); |
| 94 | } |
| 95 | |
| 96 | // We use protobuf utility `NewCallback' to create a closure object |
| 97 | // that will call our callback `HandleEchoResponse'. This closure |
| 98 | // will automatically delete itself after being called once |
| 99 | google::protobuf::Closure* done = brpc::NewCallback( |
| 100 | &HandleEchoResponse, cntl, response); |
| 101 | stub.Echo(cntl, &request, response, done); |
| 102 | |
| 103 | // This is an asynchronous RPC, so we can only fetch the result |
| 104 | // inside the callback |
| 105 | sleep(1); |
| 106 | } |
| 107 | |
| 108 | LOG(INFO) << "EchoClient is going to quit"; |
| 109 | return 0; |
nothing calls this directly
no test coverage detected