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