RpcServerTest.cc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include <boost/bind.hpp>
  2. #include <boost/shared_ptr.hpp>
  3. #include <boost/asio.hpp>
  4. #include <boost/threadpool.hpp>
  5. #include <gtest/gtest.h>
  6. #include <google/protobuf/service.h>
  7. #include "Thread/CountBarrier.h"
  8. #include "Rpc/RpcClient.h"
  9. #include "Rpc/RpcServer.h"
  10. #include "Rpc/RpcSession.h"
  11. #include "Rpc/RpcServerMock.h"
  12. #include "Rpc/Echo.pb.h"
  13. namespace Egametang {
  14. static int globalPort = 10003;
  15. class MyEcho: public EchoService
  16. {
  17. public:
  18. virtual void Echo(
  19. google::protobuf::RpcController* controller,
  20. const EchoRequest* request,
  21. EchoResponse* response,
  22. google::protobuf::Closure* done)
  23. {
  24. int32 num = request->num();
  25. response->set_num(num);
  26. if (done)
  27. {
  28. done->Run();
  29. }
  30. }
  31. };
  32. static void IOServiceRun(boost::asio::io_service* ioService)
  33. {
  34. ioService->run();
  35. }
  36. class RpcServerTest: public testing::Test
  37. {
  38. protected:
  39. MethodMap& GetMethodMap(RpcServerPtr server)
  40. {
  41. return server->methods;
  42. }
  43. };
  44. TEST_F(RpcServerTest, ClientAndServer)
  45. {
  46. boost::asio::io_service ioClient;
  47. boost::asio::io_service ioServer;
  48. boost::threadpool::fifo_pool threadPool(2);
  49. auto echoSevice = boost::make_shared<MyEcho>();
  50. auto server = boost::make_shared<RpcServer>(ioServer, globalPort);
  51. // 注册service
  52. server->Register(echoSevice);
  53. ASSERT_EQ(1U, GetMethodMap(server).size());
  54. auto client = boost::make_shared<RpcClient>(ioClient, "127.0.0.1", globalPort);
  55. EchoService_Stub service(client.get());
  56. // 定义消息
  57. EchoRequest request;
  58. request.set_num(100);
  59. EchoResponse response;
  60. ASSERT_EQ(0U, response.num());
  61. // server和client分别在两个不同的线程
  62. threadPool.schedule(boost::bind(&IOServiceRun, &ioServer));
  63. // 等待server OK
  64. boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  65. threadPool.schedule(boost::bind(&IOServiceRun, &ioClient));
  66. CountBarrier barrier;
  67. service.Echo(nullptr, &request, &response,
  68. google::protobuf::NewCallback(&barrier, &CountBarrier::Signal));
  69. barrier.Wait();
  70. // 加入任务队列,等client和server stop,io_service才stop
  71. ioClient.post(boost::bind(&boost::asio::io_service::stop, &ioClient));
  72. ioServer.post(boost::bind(&boost::asio::io_service::stop, &ioServer));
  73. // 必须主动让client和server stop才能wait线程
  74. threadPool.wait();
  75. ASSERT_EQ(100, response.num());
  76. }
  77. } // namespace Egametang
  78. int main(int argc, char* argv[])
  79. {
  80. testing::InitGoogleTest(&argc, argv);
  81. return RUN_ALL_TESTS();
  82. }