Open Lighting Architecture
 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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/io/Descriptor.h>
26 #include <ola/io/SelectServerInterface.h>
27 #include <ola/network/IPV4Address.h>
28 #include <ola/network/SocketAddress.h>
29 #include <ola/network/TCPSocket.h>
30 #include <set>
31 
32 
33 namespace ola {
34 namespace network {
35 
39 class TCPConnector {
40  public:
42  ~TCPConnector();
43 
45  typedef const void* TCPConnectionID;
46 
47  TCPConnectionID Connect(const IPV4SocketAddress &endpoint,
48  const ola::TimeInterval &timeout,
49  TCPConnectCallback *callback);
50 
51  bool Cancel(TCPConnectionID id);
52  void CancelAll();
53  unsigned int ConnectionsPending() const { return m_connections.size(); }
54 
55  private:
59  class PendingTCPConnection: public ola::io::WriteFileDescriptor {
60  public:
61  PendingTCPConnection(TCPConnector *connector,
62  const IPV4Address &ip,
63  int fd,
64  TCPConnectCallback *callback)
65  : WriteFileDescriptor(),
66  ip_address(ip),
67  callback(callback),
68  timeout_id(ola::thread::INVALID_TIMEOUT),
69  m_connector(connector),
70  m_fd(fd) {
71  }
72 
73  int WriteDescriptor() const { return m_fd; }
74 
75  void PerformWrite();
76  void Close();
77 
78  const IPV4Address ip_address;
79  TCPConnectCallback *callback;
80  ola::thread::timeout_id timeout_id;
81 
82  private:
83  TCPConnector *m_connector;
84  int m_fd;
85  };
86 
87  typedef std::set<PendingTCPConnection*> ConnectionSet;
88 
90  ConnectionSet m_connections;
91 
92 
93  void SocketWritable(PendingTCPConnection *connection);
94  void FreePendingConnection(PendingTCPConnection *connection);
95  void Timeout(const ConnectionSet::iterator &iter);
96  void TimeoutEvent(PendingTCPConnection *connection);
97 };
98 } // namespace network
99 } // namespace ola
100 #endif // INCLUDE_OLA_NETWORK_TCPCONNECTOR_H_