tutorial-09-client_task.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. Copyright (c) 2020 sogou, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #include <stdio.h>
  14. #include <workflow/WFTaskFactory.h>
  15. #include "echo_pb.srpc.h"
  16. #include "workflow/WFFacilities.h"
  17. using namespace srpc;
  18. int main()
  19. {
  20. Example::SRPCClient client("127.0.0.1", 1412);
  21. EchoRequest req;
  22. req.set_message("Hello, srpc!");
  23. req.set_name("1412");
  24. auto *rpc_task = client.create_Echo_task([](EchoResponse *resp,
  25. RPCContext *ctx)
  26. {
  27. if (ctx->success())
  28. printf("%s\n", resp->DebugString().c_str());
  29. else
  30. printf("status[%d] error[%d] errmsg:%s\n",
  31. ctx->get_status_code(), ctx->get_error(), ctx->get_errmsg());
  32. });
  33. auto *http_task = WFTaskFactory::create_http_task("https://www.sogou.com",
  34. 0, 0,
  35. [](WFHttpTask *task)
  36. {
  37. if (task->get_state() == WFT_STATE_SUCCESS)
  38. {
  39. std::string body;
  40. const void *data;
  41. size_t len;
  42. task->get_resp()->get_parsed_body(&data, &len);
  43. body.assign((const char *)data, len);
  44. printf("%s\n\n", body.c_str());
  45. }
  46. else
  47. printf("Http request fail\n\n");
  48. });
  49. rpc_task->serialize_input(&req);
  50. rpc_task->log({{"event", "info"}, {"message", "rpc client task log."}});
  51. WFFacilities::WaitGroup wait_group(1);
  52. SeriesWork *series = Workflow::create_series_work(http_task, [&wait_group](const SeriesWork *) {
  53. wait_group.done();
  54. });
  55. series->push_back(rpc_task);
  56. series->start();
  57. wait_group.wait();
  58. return 0;
  59. }