network.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Copyright 2019 Google LLC
  2. //
  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. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "dap/network.h"
  15. #include "socket.h"
  16. #include <atomic>
  17. #include <mutex>
  18. #include <string>
  19. #include <thread>
  20. namespace {
  21. class Impl : public dap::net::Server {
  22. public:
  23. Impl() : stopped{true} {}
  24. ~Impl() { stop(); }
  25. bool start(int port,
  26. const OnConnect& onConnect,
  27. const OnError& onError) override {
  28. return start("localhost", port, onConnect, onError);
  29. }
  30. bool start(const char* address,
  31. int port,
  32. const OnConnect& onConnect,
  33. const OnError& onError) override {
  34. std::unique_lock<std::mutex> lock(mutex);
  35. stopWithLock();
  36. socket = std::unique_ptr<dap::Socket>(
  37. new dap::Socket(address, std::to_string(port).c_str()));
  38. if (!socket->isOpen()) {
  39. onError("Failed to open socket");
  40. return false;
  41. }
  42. stopped = false;
  43. thread = std::thread([=] {
  44. while (true) {
  45. if (auto rw = socket->accept()) {
  46. onConnect(rw);
  47. continue;
  48. }
  49. if (!stopped) {
  50. onError("Failed to accept connection");
  51. }
  52. break;
  53. };
  54. });
  55. return true;
  56. }
  57. void stop() override {
  58. std::unique_lock<std::mutex> lock(mutex);
  59. stopWithLock();
  60. }
  61. private:
  62. bool isRunning() { return !stopped; }
  63. void stopWithLock() {
  64. if (!stopped.exchange(true)) {
  65. socket->close();
  66. thread.join();
  67. }
  68. }
  69. std::mutex mutex;
  70. std::thread thread;
  71. std::unique_ptr<dap::Socket> socket;
  72. std::atomic<bool> stopped;
  73. OnError errorHandler;
  74. };
  75. } // anonymous namespace
  76. namespace dap {
  77. namespace net {
  78. std::unique_ptr<Server> Server::create() {
  79. return std::unique_ptr<Server>(new Impl());
  80. }
  81. std::shared_ptr<ReaderWriter> connect(const char* addr,
  82. int port,
  83. uint32_t timeoutMillis) {
  84. return Socket::connect(addr, std::to_string(port).c_str(), timeoutMillis);
  85. }
  86. } // namespace net
  87. } // namespace dap