#ifndef LISTENTHREAD_H
#define LISTENTHREAD_H
// #include <standard library headers>
// #include <other library headers>
// #include "customer headers"
#include "ServerSocket.h"
#include "Thread.hpp"
class ResponseThread;
/**
* description
*/
class ListenThread : public Thread
{
public:
ListenThread(int port);
virtual ~ListenThread();
public:
virtual int Run();
protected:
virtual ResponseThread* CreateResponseThread() = 0;
private:
void CleanCompleteThread();
bool EarseOneCompleteThread();
void CleanAllThread();
private:
int m_nPort;
ThreadList mThreads;
};
#endif
// #include <standard library headers>
#include <algorithm>
// #include <other library headers>
// #include "customer headers"
#include "ListenThread.h"
#include "ResponseThread.h"
/**
* description
*/
ListenThread::ListenThread(int port) : m_nPort(port)
{
}
/**
* description
*/
ListenThread::~ListenThread()
{
SetStop();
WaitForEnd();
}
int ListenThread::Run()
{
sock::ServerSocket listenSocket(m_nPort);
ResponseThread* rt = NULL;
while (!GetStop())
{
try
{
if (rt == NULL)
{
rt = CreateResponseThread();
}
listenSocket.Accept(rt->GetSocket(), 0, 50000);
rt->Start();
mThreads.push_back(rt);
rt = NULL;
}
catch (...)
{
continue;
}
//clean the thread which is complete
CleanCompleteThread();
}
delete rt;
rt = NULL;
CleanAllThread();
return 1;
}
void ListenThread::CleanCompleteThread()
{
while (EarseOneCompleteThread())
{
}
}
bool ListenThread::EarseOneCompleteThread()
{
for (ThreadList::iterator it = mThreads.begin();
it != mThreads.end(); it++)
{
Thread* pThread = *it;
if (pThread != NULL)
{
if (pThread->WaitForEnd(0))
{
delete pThread;
pThread = NULL;
mThreads.erase(it);
return true;
}
}
}
return false;
}
void ListenThread::CleanAllThread()
{
}