Open Lighting Architecture  0.9.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TCPConnector.h
1 /*
2  * This library is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU Lesser General Public
4  * License as published by the Free Software Foundation; either
5  * version 2.1 of the License, or (at your option) any later version.
6  *
7  * This library is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  * Lesser General Public License for more details.
11  *
12  * You should have received a copy of the GNU Lesser General Public
13  * License along with this library; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15  *
16  * TCPConnector.h.h
17  * Copyright (C) 2012 Simon Newton
18  */
19 
20 #ifndef INCLUDE_OLA_NETWORK_TCPCONNECTOR_H_
21 #define INCLUDE_OLA_NETWORK_TCPCONNECTOR_H_
22 
23 #include <ola/Callback.h>
24 #include <ola/Clock.h>
25 #include <ola/base/Macro.h>
26 #include <ola/io/Descriptor.h>
27 #include <ola/io/SelectServerInterface.h>
30 #include <ola/network/TCPSocket.h>
31 #include <set>
32 #include <vector>
33 
34 namespace ola {
35 namespace network {
36 
40 class TCPConnector {
41  public:
49 
55  typedef const void* TCPConnectionID;
56 
62 
63  ~TCPConnector();
64 
79  const ola::TimeInterval &timeout,
80  TCPConnectCallback *callback);
81 
91  bool Cancel(TCPConnectionID id);
92 
96  void CancelAll();
97 
101  unsigned int ConnectionsPending() const { return m_connections.size(); }
102 
103  private:
107  class PendingTCPConnection: public ola::io::WriteFileDescriptor {
108  public:
109  PendingTCPConnection(TCPConnector *connector,
110  const IPV4Address &ip,
111  int fd,
112  TCPConnectCallback *callback);
113 
114  ola::io::DescriptorHandle WriteDescriptor() const { return m_handle; }
115 
116  void PerformWrite();
117  void Close();
118 
119  const IPV4Address ip_address;
120  TCPConnectCallback *callback;
121  ola::thread::timeout_id timeout_id;
122 
123  private:
124  TCPConnector *m_connector;
125  ola::io::DescriptorHandle m_handle;
126  };
127 
128  typedef std::set<PendingTCPConnection*> ConnectionSet;
129  typedef std::vector<PendingTCPConnection*> ConnectionList;
130 
132  ConnectionSet m_connections;
133  ConnectionList m_orphaned_connections;
134 
135  void SocketWritable(PendingTCPConnection *connection);
136  void FreePendingConnection(PendingTCPConnection *connection);
137  void Timeout(const ConnectionSet::iterator &iter);
138  void TimeoutEvent(PendingTCPConnection *connection);
139  void CleanUpOrphans();
140 
141  DISALLOW_COPY_AND_ASSIGN(TCPConnector);
142 };
143 } // namespace network
144 } // namespace ola
145 #endif // INCLUDE_OLA_NETWORK_TCPCONNECTOR_H_