1 /******************************************************************************
3 * Copyright (C) 2012 Icinga Development Team (http://www.icinga.org/) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
22 using namespace icinga;
25 * Constructor for the TcpServer class.
27 TcpServer::TcpServer(void)
29 m_ClientFactory = bind(&TcpClientFactory, RoleInbound);
33 * Sets the client factory.
35 * @param clientFactory The client factory function.
37 void TcpServer::SetClientFactory(function<TcpClient::Ptr()> clientFactory)
39 m_ClientFactory = clientFactory;
43 * Retrieves the client factory.
45 * @returns The client factory function.
47 function<TcpClient::Ptr()> TcpServer::GetFactoryFunction(void) const
49 return m_ClientFactory;
53 * Registers the TCP server and starts processing events for it.
55 void TcpServer::Start(void)
59 OnReadable.connect(bind(&TcpServer::ReadableEventHandler, this, _1));
63 * Starts listening for incoming client connections.
65 void TcpServer::Listen(void)
67 int rc = listen(GetFD(), SOMAXCONN);
70 HandleSocketError(SocketException(
71 "listen() failed", GetError()));
77 * Accepts a new client and creates a new client object for it
78 * using the client factory function.
80 * @param - Event arguments.
83 int TcpServer::ReadableEventHandler(const EventArgs&)
86 sockaddr_storage addr;
87 socklen_t addrlen = sizeof(addr);
89 fd = accept(GetFD(), (sockaddr *)&addr, &addrlen);
92 HandleSocketError(SocketException(
93 "accept() failed", GetError()));
97 NewClientEventArgs nea;
98 nea.Source = shared_from_this();
99 nea.Client = static_pointer_cast<TcpSocket>(m_ClientFactory());
100 nea.Client->SetFD(fd);
108 * Checks whether the TCP server wants to read (i.e. accept new clients).
112 bool TcpServer::WantsToRead(void) const