network.h 2.0 KB

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