tutorial-10-server_async.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 <signal.h>
  14. #include <workflow/WFTaskFactory.h>
  15. #include "echo_pb.srpc.h"
  16. #include "workflow/WFFacilities.h"
  17. using namespace srpc;
  18. static WFFacilities::WaitGroup wait_group(1);
  19. class ExampleServiceImpl : public Example::Service
  20. {
  21. public:
  22. void Echo(EchoRequest *req, EchoResponse *resp, RPCContext *ctx) override
  23. {
  24. ctx->set_compress_type(RPCCompressGzip);
  25. ctx->log({{"event", "info"}, {"message", "rpc server echo() end."}});
  26. auto *task = WFTaskFactory::create_http_task("https://www.sogou.com",
  27. 0, 0,
  28. [req, resp](WFHttpTask *task)
  29. {
  30. if (task->get_state() == WFT_STATE_SUCCESS)
  31. {
  32. const void *data;
  33. size_t len;
  34. task->get_resp()->get_parsed_body(&data, &len);
  35. resp->mutable_message()->assign((const char *)data, len);
  36. }
  37. else
  38. resp->set_message("Error: " + std::to_string(task->get_error()));
  39. printf("Server Echo()\nget_req:\n%s\nset_resp:\n%s\n",
  40. req->DebugString().c_str(), resp->DebugString().c_str());
  41. });
  42. ctx->get_series()->push_back(task);
  43. }
  44. };
  45. static void sig_handler(int signo)
  46. {
  47. wait_group.done();
  48. }
  49. int main(int argc, char *argv[])
  50. {
  51. GOOGLE_PROTOBUF_VERIFY_VERSION;
  52. signal(SIGINT, sig_handler);
  53. signal(SIGTERM, sig_handler);
  54. SRPCServer server;
  55. ExampleServiceImpl impl;
  56. server.add_service(&impl);
  57. if (server.start(1412) == 0)
  58. {
  59. printf("Asynchronous server with HTTP requests is running on 1412\n"
  60. "Try ./client_task or ./srpc_pb_client to trigger this example.\n\n");
  61. wait_group.wait();
  62. server.stop();
  63. }
  64. else
  65. perror("server start");
  66. google::protobuf::ShutdownProtobufLibrary();
  67. return 0;
  68. }