1 // Copyright (C) 2021 The Android Open Source Project
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 // http://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 #pragma once
15 
16 #include <functional>
17 #include <memory>
18 
19 #include "net/async_data_channel.h"
20 
21 namespace android {
22 namespace net {
23 
24 class AsyncDataChannelServer;
25 
26 // Callback thas is called when a new client connection has been accepted.
27 using ConnectCallback = std::function<void(std::shared_ptr<AsyncDataChannel>,
28                                            AsyncDataChannelServer* server)>;
29 
30 // An AsyncDataChannelServer is capable of listening to incoming connections.
31 //
32 // A Callback will be invoked whenever a new connection has been accepted.
33 class AsyncDataChannelServer {
34  public:
35   // Destructor.
36   virtual ~AsyncDataChannelServer() = default;
37 
38   // Start listening for new connections. The callback will be invoked
39   // when a new socket has been accepted.
40   //
41   // errno will be set in case of failure.
42   virtual bool StartListening() = 0;
43 
44   // Stop listening for new connections. The callback will not be
45   // invoked, and sockets will not be accepted.
46   //
47   // This DOES not disconnect the server, and connections can still
48   // be queued up.
49   virtual void StopListening() = 0;
50 
51   // Disconnects the server, no new connections are possible.
52   // The callback will never be invoked again.
53   virtual void Close() = 0;
54 
55   // True if this server is connected and can accept incoming
56   // connections.
57   virtual bool Connected() = 0;
58 
59   // Registers the callback that should be invoked whenever a new socket was
60   // accepted.
61   //
62   // Before the callback the server should have stopped listening for new
63   // incoming connections. The callee is responsible for calling StartListening
64   // if needed.
SetOnConnectCallback(const ConnectCallback & callback)65   void SetOnConnectCallback(const ConnectCallback& callback) {
66     callback_ = callback;
67   };
68 
69  protected:
70   ConnectCallback callback_;
71 };
72 
73 }  // namespace net
74 }  // namespace android
75