RPC流程三 - Client端编写

Orenda ·
更新时间:2024-11-13
· 897 次阅读

流程二:https://blog.csdn.net/wd3cwg38/article/details/104417616

int main() { echo::EchoRequest request; echo::EchoResponse response; request.set_message("hello tonull, from client"); char* ip = argv[1]; char* port = argv[2]; std::string addr = std::string(ip) + ":" + std::string(port); RpcChannel rpc_channel(addr); echo::EchoServer_Stub stub(&rpc_channel); RpcController controller; stub.Echo(&controller, &request, &response, nullptr); if (controller.Failed()) std::cout << "request failed: %s" << controller.ErrorText().c_str(); else std::cout << "resp: " << response.message() << std::endl; return 0; } - google实现 // google::protobuf::RpcChannel class RpcChannel {} // google::protobuf::RpcController class RpcController {} - Client端实现

Coder实现一:RpcChannel

class RpcChannel : public google::protobuf::RpcChannel { public: RpcChannel(std::string& server_addr); virtual ~RpcChannel(); virtual void CallMethod( const ::google::protobuf::MethodDescriptor* method, ::google::protobuf::RpcController* controller, const ::google::protobuf::Message* request, ::google::protobuf::Message* response, ::google::protobuf::Closure* done ); private: RpcChannelImpl* impl_; // RpcChannel具体实现 };

Coder实现二:RpcChannelImpl

// 主要实现CallMethod()用于调用服务 class RpcChannelImpl : public google::protobuf::RpcChannel { public: RpcChannelImpl(std::string& server_addr) {} virtual ~RpcChannelImpl() {} virtual void Init(std::string& server_addr); virtual void CallMethod( const ::google::protobuf::MethodDescriptor* method, ::google::protobuf::RpcController* controller, const ::google::protobuf::Message* request, ::google::protobuf::Message* response, ::google::protobuf::Closure* done ); private: std::string server_addr_; boost::shared_ptr io_; boost::shared_ptr socket_; }; // client RpcChannel rpc_channel(addr); echo::EchoServer_Stub stub(&rpc_channel); // client CallMethod stub.Echo(&controller, &request, &response, nullptr);

Coder实现三:RpcController

// 用于对RPC过程中的信息进行反馈 class RpcController : public google::protobuf::RpcController { public: RpcController() { Reset(); } virtual ~RpcController() {} virtual void Reset() { is_failed_ = false; error_code_ = ""; } virtual bool Failed() const { return is_failed_; } virtual void SetFailed(const std::string& reason) { is_failed_ = true; error_code_ = reason;} virtual std::string ErrorText() const { return error_code_; } virtual void StartCancel() { }; virtual bool IsCanceled() const { return false; }; virtual void NotifyOnCancel(::google::protobuf::Closure* /* callback */) { }; private: bool is_failed_; std::string error_code_; }; - Client端实现流程 编写EchoRequest 通过RpcChannelstub与服务端进行通信 - 参考文献

1、RPC流程介绍 - https://izualzhy.cn/demo-protobuf-rpc


作者:k2z



rpc

需要 登录 后方可回复, 如果你还没有账号请 注册新账号