server.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "server.h"
  2. #include <util/system/thread.h>
  3. namespace NMock {
  4. class TMockServer::TCallBack: public THttpServer::ICallBack {
  5. TGenerator Generator_;
  6. TClientRequest* CreateClient() override {
  7. return Generator_();
  8. }
  9. public:
  10. void SetGenerator(TGenerator generator) {
  11. Generator_ = generator;
  12. }
  13. TCallBack(TGenerator& generator)
  14. : Generator_(generator)
  15. {
  16. }
  17. };
  18. static THttpServerOptions createDefaultOptions(ui16 port) {
  19. THttpServerOptions o;
  20. o.AddBindAddress("localhost", port);
  21. o.SetThreads(1);
  22. o.SetMaxConnections(300);
  23. o.SetMaxQueueSize(30);
  24. return o;
  25. }
  26. TMockServer::TMockServer(ui16 port, TGenerator generator)
  27. : TMockServer(createDefaultOptions(port), generator)
  28. {
  29. }
  30. TMockServer::TMockServer(const THttpServerOptions& options, TGenerator generator)
  31. : Cb_(MakeHolder<TCallBack>(generator))
  32. , Server_(MakeHolder<THttpServer>(Cb_.Get(), options))
  33. , Thread_(MakeHolder<TThread>(Worker, this))
  34. , Ev_(MakeHolder<TAutoEvent>())
  35. {
  36. Thread_->Start();
  37. Ev_->Wait();
  38. }
  39. TMockServer::~TMockServer() {
  40. Server_->Stop();
  41. Thread_->Join();
  42. }
  43. size_t TMockServer::GetClientCount() const {
  44. return Server_->GetClientCount();
  45. }
  46. void TMockServer::SetGenerator(TMockServer::TGenerator generator) {
  47. Cb_->SetGenerator(generator);
  48. }
  49. void* TMockServer::Worker(void* arg) {
  50. TMockServer& this_ = *static_cast<TMockServer*>(arg);
  51. this_.Server_->Start();
  52. this_.Ev_->Signal();
  53. this_.Server_->Wait();
  54. return nullptr;
  55. }
  56. }