icinga2/base/tcpserver.cpp

109 lines
1.8 KiB
C++
Raw Normal View History

2012-03-28 13:24:49 +02:00
#include "i2-base.h"
using namespace icinga;
2012-05-08 15:36:28 +02:00
/**
* TCPServer
*
* Constructor for the TCPServer class.
*/
2012-03-28 13:24:49 +02:00
TCPServer::TCPServer(void)
{
2012-04-24 14:02:15 +02:00
m_ClientFactory = bind(&TCPClientFactory, RoleInbound);
2012-03-28 13:24:49 +02:00
}
2012-05-08 15:36:28 +02:00
/**
* SetClientFactory
*
* Sets the client factory.
*
* @param clientFactory The client factory function.
*/
2012-04-24 14:02:15 +02:00
void TCPServer::SetClientFactory(function<TCPClient::Ptr()> clientFactory)
2012-03-28 13:24:49 +02:00
{
m_ClientFactory = clientFactory;
}
2012-05-08 15:36:28 +02:00
/**
* GetFactoryFunction
*
* Retrieves the client factory.
*
* @returns The client factory function.
*/
2012-04-24 14:02:15 +02:00
function<TCPClient::Ptr()> TCPServer::GetFactoryFunction(void) const
2012-03-28 13:24:49 +02:00
{
return m_ClientFactory;
}
2012-05-08 15:36:28 +02:00
/**
* Start
*
* Registers the TCP server and starts processing events for it.
*/
2012-03-28 13:24:49 +02:00
void TCPServer::Start(void)
{
TCPSocket::Start();
2012-04-03 11:13:17 +02:00
OnReadable += bind_weak(&TCPServer::ReadableEventHandler, shared_from_this());
2012-03-28 13:24:49 +02:00
}
2012-05-08 15:36:28 +02:00
/**
* Listen
*
* Starts listening for incoming client connections.
*/
2012-03-28 13:24:49 +02:00
void TCPServer::Listen(void)
{
int rc = listen(GetFD(), SOMAXCONN);
if (rc < 0) {
2012-05-07 13:48:17 +02:00
HandleSocketError();
return;
}
2012-03-28 13:24:49 +02:00
}
2012-05-08 15:36:28 +02:00
/**
* ReadableEventHandler
*
* Accepts a new client and creates a new client object for it
* using the client factory function.
*
* @param ea Event arguments.
* @returns 0
*/
2012-04-18 15:22:25 +02:00
int TCPServer::ReadableEventHandler(const EventArgs& ea)
2012-03-28 13:24:49 +02:00
{
int fd;
2012-04-27 09:54:07 +02:00
sockaddr_storage addr;
2012-03-28 13:24:49 +02:00
socklen_t addrlen = sizeof(addr);
fd = accept(GetFD(), (sockaddr *)&addr, &addrlen);
2012-04-22 16:45:31 +02:00
if (fd < 0) {
HandleSocketError();
return 0;
2012-04-18 15:22:25 +02:00
}
NewClientEventArgs nea;
nea.Source = shared_from_this();
nea.Client = static_pointer_cast<TCPSocket>(m_ClientFactory());
nea.Client->SetFD(fd);
nea.Client->Start();
2012-03-28 13:24:49 +02:00
OnNewClient(nea);
return 0;
}
2012-05-08 15:36:28 +02:00
/**
* WantsToRead
*
* Checks whether the TCP server wants to read (i.e. accept new clients).
*
* @returns true
*/
2012-03-28 13:24:49 +02:00
bool TCPServer::WantsToRead(void) const
{
return true;
}