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