1
0

protorpc_client.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. * proto rpc client
  3. *
  4. * @build make protorpc
  5. * @server bin/protorpc_server 1234
  6. * @client bin/protorpc_client 127.0.0.1 1234 add 1 2
  7. *
  8. */
  9. #include "TcpClient.h"
  10. #include <mutex>
  11. #include <condition_variable>
  12. using namespace hv;
  13. #include "protorpc.h"
  14. #include "generated/base.pb.h"
  15. #include "generated/calc.pb.h"
  16. #include "generated/login.pb.h"
  17. // valgrind --leak-check=full --show-leak-kinds=all
  18. class ProtobufRAII {
  19. public:
  20. ProtobufRAII() {
  21. }
  22. ~ProtobufRAII() {
  23. google::protobuf::ShutdownProtobufLibrary();
  24. }
  25. };
  26. static ProtobufRAII s_protobuf;
  27. namespace protorpc {
  28. typedef std::shared_ptr<protorpc::Request> RequestPtr;
  29. typedef std::shared_ptr<protorpc::Response> ResponsePtr;
  30. enum ProtoRpcResult {
  31. kRpcSuccess = 0,
  32. kRpcTimeout = -1,
  33. kRpcError = -2,
  34. kRpcNoResult = -3,
  35. kRpcParseError = -4,
  36. };
  37. class ProtoRpcContext {
  38. public:
  39. protorpc::RequestPtr req;
  40. protorpc::ResponsePtr res;
  41. private:
  42. std::mutex _mutex;
  43. std::condition_variable _cond;
  44. public:
  45. void wait(int timeout_ms) {
  46. std::unique_lock<std::mutex> locker(_mutex);
  47. _cond.wait_for(locker, std::chrono::milliseconds(timeout_ms));
  48. }
  49. void notify() {
  50. _cond.notify_one();
  51. }
  52. };
  53. typedef std::shared_ptr<ProtoRpcContext> ContextPtr;
  54. class ProtoRpcClient : public TcpClient {
  55. public:
  56. ProtoRpcClient() : TcpClient()
  57. {
  58. connect_state = kInitialized;
  59. setConnectTimeout(5000);
  60. ReconnectInfo reconn;
  61. reconn.min_delay = 1000;
  62. reconn.max_delay = 10000;
  63. reconn.delay_policy = 2;
  64. setReconnect(&reconn);
  65. // init protorpc_unpack_setting
  66. unpack_setting_t protorpc_unpack_setting;
  67. memset(&protorpc_unpack_setting, 0, sizeof(unpack_setting_t));
  68. protorpc_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD;
  69. protorpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH;
  70. protorpc_unpack_setting.body_offset = PROTORPC_HEAD_LENGTH;
  71. protorpc_unpack_setting.length_field_offset = PROTORPC_HEAD_LENGTH_FIELD_OFFSET;
  72. protorpc_unpack_setting.length_field_bytes = PROTORPC_HEAD_LENGTH_FIELD_BYTES;
  73. protorpc_unpack_setting.length_field_coding = ENCODE_BY_BIG_ENDIAN;
  74. setUnpack(&protorpc_unpack_setting);
  75. onConnection = [this](const SocketChannelPtr& channel) {
  76. std::string peeraddr = channel->peeraddr();
  77. if (channel->isConnected()) {
  78. connect_state = kConnected;
  79. printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  80. } else {
  81. connect_state = kDisconnectd;
  82. printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd());
  83. }
  84. };
  85. onMessage = [this](const SocketChannelPtr& channel, Buffer* buf) {
  86. // protorpc_unpack
  87. protorpc_message msg;
  88. memset(&msg, 0, sizeof(msg));
  89. int packlen = protorpc_unpack(&msg, buf->data(), buf->size());
  90. if (packlen < 0) {
  91. printf("protorpc_unpack failed!\n");
  92. return;
  93. }
  94. assert(packlen == buf->size());
  95. if (protorpc_head_check(&msg.head) != 0) {
  96. printf("protorpc_head_check failed!\n");
  97. return;
  98. }
  99. // Response::ParseFromArray
  100. protorpc::ResponsePtr res(new protorpc::Response);
  101. if (!res->ParseFromArray(msg.body, msg.head.length)) {
  102. return;
  103. }
  104. // id => res
  105. calls_mutex.lock();
  106. auto iter = calls.find(res->id());
  107. if (iter == calls.end()) {
  108. return;
  109. }
  110. auto ctx = iter->second;
  111. calls_mutex.unlock();
  112. ctx->res = res;
  113. ctx->notify();
  114. };
  115. }
  116. int connect(int port, const char* host = "127.0.0.1") {
  117. createsocket(port, host);
  118. connect_state = kConnecting;
  119. start();
  120. return 0;
  121. }
  122. protorpc::ResponsePtr call(protorpc::RequestPtr& req, int timeout_ms = 10000) {
  123. if (connect_state != kConnected) {
  124. return NULL;
  125. }
  126. static std::atomic<uint64_t> s_id = ATOMIC_VAR_INIT(0);
  127. req->set_id(++s_id);
  128. req->id();
  129. auto ctx = new protorpc::ProtoRpcContext;
  130. ctx->req = req;
  131. calls[req->id()] = protorpc::ContextPtr(ctx);
  132. // Request::SerializeToArray + protorpc_pack
  133. protorpc_message msg;
  134. protorpc_message_init(&msg);
  135. msg.head.length = req->ByteSize();
  136. int packlen = protorpc_package_length(&msg.head);
  137. unsigned char* writebuf = NULL;
  138. HV_ALLOC(writebuf, packlen);
  139. packlen = protorpc_pack(&msg, writebuf, packlen);
  140. if (packlen > 0) {
  141. printf("%s\n", req->DebugString().c_str());
  142. req->SerializeToArray(writebuf + PROTORPC_HEAD_LENGTH, msg.head.length);
  143. channel->write(writebuf, packlen);
  144. }
  145. HV_FREE(writebuf);
  146. // wait until response come or timeout
  147. ctx->wait(timeout_ms);
  148. auto res = ctx->res;
  149. calls_mutex.lock();
  150. calls.erase(req->id());
  151. calls_mutex.unlock();
  152. if (res == NULL) {
  153. printf("RPC timeout!\n");
  154. } else if (res->has_error()) {
  155. printf("RPC error:\n%s\n", res->error().DebugString().c_str());
  156. }
  157. return res;
  158. }
  159. int calc(const char* method, int num1, int num2, int& out) {
  160. protorpc::RequestPtr req(new protorpc::Request);
  161. // method
  162. req->set_method(method);
  163. // params
  164. protorpc::CalcParam param1, param2;
  165. param1.set_num(num1);
  166. param2.set_num(num2);
  167. req->add_params()->assign(param1.SerializeAsString());
  168. req->add_params()->assign(param2.SerializeAsString());
  169. auto res = call(req);
  170. if (res == NULL) return kRpcTimeout;
  171. if (res->has_error()) return kRpcError;
  172. if (res->result().empty()) return kRpcNoResult;
  173. protorpc::CalcResult result;
  174. if (!result.ParseFromString(res->result())) return kRpcParseError;
  175. out = result.num();
  176. return kRpcSuccess;
  177. }
  178. int login(const protorpc::LoginParam& param, protorpc::LoginResult* result) {
  179. protorpc::RequestPtr req(new protorpc::Request);
  180. // method
  181. req->set_method("login");
  182. // params
  183. req->add_params()->assign(param.SerializeAsString());
  184. auto res = call(req);
  185. if (res == NULL) return kRpcTimeout;
  186. if (res->has_error()) return kRpcError;
  187. if (res->result().empty()) return kRpcNoResult;
  188. if (!result->ParseFromString(res->result())) return kRpcParseError;
  189. return kRpcSuccess;
  190. }
  191. enum {
  192. kInitialized,
  193. kConnecting,
  194. kConnected,
  195. kDisconnectd,
  196. } connect_state;
  197. std::map<uint64_t, protorpc::ContextPtr> calls;
  198. std::mutex calls_mutex;
  199. };
  200. }
  201. int main(int argc, char** argv) {
  202. if (argc < 6) {
  203. printf("Usage: %s host port method param1 param2\n", argv[0]);
  204. printf("method = [add, sub, mul, div]\n");
  205. printf("Examples:\n");
  206. printf(" %s 127.0.0.1 1234 add 1 2\n", argv[0]);
  207. printf(" %s 127.0.0.1 1234 div 1 0\n", argv[0]);
  208. return -10;
  209. }
  210. const char* host = argv[1];
  211. int port = atoi(argv[2]);
  212. const char* method = argv[3];
  213. const char* param1 = argv[4];
  214. const char* param2 = argv[5];
  215. protorpc::ProtoRpcClient cli;
  216. cli.connect(port, host);
  217. while (cli.connect_state == protorpc::ProtoRpcClient::kConnecting) hv_msleep(1);
  218. if (cli.connect_state == protorpc::ProtoRpcClient::kDisconnectd) {
  219. return -20;
  220. }
  221. // test login
  222. {
  223. protorpc::LoginParam param;
  224. param.set_username("admin");
  225. param.set_password("123456");
  226. protorpc::LoginResult result;
  227. if (cli.login(param, &result) == protorpc::kRpcSuccess) {
  228. printf("login success!\n");
  229. printf("%s\n", result.DebugString().c_str());
  230. } else {
  231. printf("login failed!\n");
  232. }
  233. }
  234. // test calc
  235. {
  236. int num1 = atoi(param1);
  237. int num2 = atoi(param2);
  238. int result = 0;
  239. if (cli.calc(method, num1, num2, result) == protorpc::kRpcSuccess) {
  240. printf("calc success!\n");
  241. printf("%d %s %d = %d\n", num1, method, num2, result);
  242. } else {
  243. printf("calc failed!\n");
  244. }
  245. }
  246. return 0;
  247. }