network.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #ifndef dap_network_h
  15. #define dap_network_h
  16. #include <functional>
  17. #include <memory>
  18. #include <stdint.h>
  19. namespace dap {
  20. class ReaderWriter;
  21. namespace net {
  22. // connect() connects to the given TCP address and port.
  23. // If timeoutMillis is non-zero and no connection was made before timeoutMillis
  24. // milliseconds, then nullptr is returned.
  25. std::shared_ptr<ReaderWriter> connect(const char* addr,
  26. int port,
  27. uint32_t timeoutMillis = 0);
  28. // Server implements a basic TCP server.
  29. class Server {
  30. // ignoreErrors() matches the OnError signature, and does nothing.
  31. static inline void ignoreErrors(const char*) {}
  32. public:
  33. using OnError = std::function<void(const char*)>;
  34. using OnConnect = std::function<void(const std::shared_ptr<ReaderWriter>&)>;
  35. virtual ~Server() = default;
  36. // create() constructs and returns a new Server.
  37. static std::unique_ptr<Server> create();
  38. // start() begins listening for connections on the given port.
  39. // callback will be called for each connection.
  40. // onError will be called for any connection errors.
  41. virtual bool start(int port,
  42. const OnConnect& callback,
  43. const OnError& onError = ignoreErrors) = 0;
  44. // stop() stops listening for connections.
  45. // stop() is implicitly called on destruction.
  46. virtual void stop() = 0;
  47. };
  48. } // namespace net
  49. } // namespace dap
  50. #endif // dap_network_h