2012-03-28 13:24:49 +02:00
|
|
|
#include "i2-base.h"
|
|
|
|
|
|
|
|
using namespace icinga;
|
|
|
|
|
|
|
|
TCPServer::TCPServer(void)
|
|
|
|
{
|
|
|
|
m_ClientFactory = factory<TCPClient>;
|
|
|
|
}
|
|
|
|
|
|
|
|
void TCPServer::SetClientFactory(factory_function clientFactory)
|
|
|
|
{
|
|
|
|
m_ClientFactory = clientFactory;
|
|
|
|
}
|
|
|
|
|
|
|
|
factory_function TCPServer::GetFactoryFunction(void)
|
|
|
|
{
|
|
|
|
return m_ClientFactory;
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
void TCPServer::Listen(void)
|
|
|
|
{
|
2012-04-04 12:22:46 +02:00
|
|
|
int rc = listen(GetFD(), SOMAXCONN);
|
|
|
|
|
|
|
|
if (rc < 0) {
|
|
|
|
Close();
|
|
|
|
return;
|
|
|
|
}
|
2012-03-28 13:24:49 +02:00
|
|
|
}
|
|
|
|
|
2012-04-18 15:22:25 +02:00
|
|
|
int TCPServer::ReadableEventHandler(const EventArgs& ea)
|
2012-03-28 13:24:49 +02:00
|
|
|
{
|
|
|
|
int fd;
|
|
|
|
sockaddr_in addr;
|
|
|
|
socklen_t addrlen = sizeof(addr);
|
|
|
|
|
|
|
|
fd = accept(GetFD(), (sockaddr *)&addr, &addrlen);
|
|
|
|
|
2012-04-18 15:22:25 +02:00
|
|
|
if (fd == INVALID_SOCKET) {
|
|
|
|
SocketErrorEventArgs sea;
|
|
|
|
#ifdef _WIN32
|
|
|
|
sea.Code = WSAGetLastError();
|
|
|
|
#else /* _WIN32 */
|
|
|
|
sea.Code = errno;
|
|
|
|
#endif /* _WIN32 */
|
|
|
|
sea.Message = FormatErrorCode(sea.Code);
|
|
|
|
|
|
|
|
OnError(sea);
|
|
|
|
|
|
|
|
Close();
|
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool TCPServer::WantsToRead(void) const
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|