示例#1
0
void VNCviewerApp32::NewConnection(TCHAR *host, int port) {
	int retries = 0;
	ClientConnection *pcc;
	ClientConnection *old_pcc;

	pcc = new ClientConnection(this, host, port);
	while (retries < MAX_AUTH_RETRIES) {
		try {
			pcc->Run();
			return;
		} catch (AuthException &e) {
			e.Report();
			// If the connection count drops to zero, the app exits.
			old_pcc = pcc;
			pcc = new ClientConnection(this, host, port);
			// Get the previous options for the next try.
			pcc->CopyOptions(old_pcc);
			delete old_pcc;
		} catch (Exception &e) {
			e.Report();	
			break;
		}
		retries++;
	}
	delete pcc;
}
示例#2
0
	int32 _Thread()
	{
		// finish connection initialization
		User* user = NULL;
		status_t error = fConnectionListener->FinishInitialization(
			fConnection, fServer->GetSecurityContext(), &user);
		// create a client connection
		ClientConnection* clientConnection = NULL;
		if (error == B_OK) {
			clientConnection = new(std::nothrow) ClientConnection(fConnection,
				fServer->GetSecurityContext(), user, fServer);
			if (!clientConnection)
				error = B_NO_MEMORY;
		}
		if (error == B_OK) {
			fConnection = NULL;	// connection belongs to client connection now
			error = clientConnection->Init();
		}
		// add the client connection to the server
		if (error == B_OK)
			error = fServer->_AddClientConnection(clientConnection);
		// cleanup on error
		if (error != B_OK)
			delete clientConnection;
		delete this;
		return 0;
	}
/** @brief add a client socket into select pool
 *
 *  @param connfd client socket
 *  @param pool select pool
 *  @return void
 */
void SelPool::add_client(int connfd, string addr)
{
    nready--;
    
    printf("adding client socket %d ...\n", connfd);

    /* Add the descriptor to descriptor set */
    if (connfd > maxfd) {
        maxfd = connfd;
    }
    FD_SET(connfd, &read_set);

    /* create a new ClientConnection Object and add it to client list */
    ClientConnection *newClient = 
                     new ClientConnection(connfd,
                                          BUF_SIZE,
                                          port,
                                          addr,
                                          ClientConnection::T_HTTP);
    
    /* add request for this ClientConnection */
    newClient->setRequest(new HTTPRequest(newClient, port, addr.c_str(), 0));

    printf("BUF_SIZE = %d\n", BUF_SIZE);
    clients.push_back(newClient);
    //cout << "added\n";
}
示例#4
0
文件: Server.cpp 项目: envy/Mineserv
	/**
	 * Erstellt eine neue Verbindung
	 */
	void Server::createCon(boost::asio::ip::tcp::socket* sock, Server* srv, std::string ip)
	{
		ClientConnection* client = new ClientConnection(sock, srv, ip, srv->curId++);
		srv->cons.push_back(client);
		client->handleClient();
		delete client;
	}
示例#5
0
void ClientConnection::processTalk(const Atlas::Objects::Operation::Talk& tk)
{
    if (m_server->m_rooms.count(tk->getTo()))
        return m_server->talkInRoom(tk, tk->getTo());
    
    if (m_server->m_accounts.count(tk->getTo())) {
        ClientConnection* cc = m_server->getConnectionForAccount(tk->getTo());
        if (!cc) {
            sendError("oog chat: account is offline", tk);
            return;
        }
        
        Sound snd;
        snd->setFrom(m_account); 
        snd->setArgs1(tk);
        snd->setTo(cc->m_account);
        cc->send(snd);
        return;
    }
    
    if (tk->getTo().empty()) {
        // lobby chat
        return m_server->talkInRoom(tk, "_lobby");
    }
    
    sendError("bad TO for OOG TALK op: " + tk->getTo(), tk);
}
void VNCviewerApp32::NewConnection() {
	ClientConnection *pcc = new ClientConnection(this);
	try {
		pcc->Run();
	} catch (Exception &e) {
//		DestroyWindow(pcc->m_hwndMain);
		pcc->CloseWindows();
		e.Report();	
		delete pcc;
	}
}
示例#7
0
void VNCviewerApp32::NewConnection(bool Is_Listening,TCHAR *host, int port) {
    ClientConnection *pcc = new ClientConnection(this, host,port);
    try {
        pcc->m_Is_Listening=Is_Listening;
        pcc->Run();
    } catch (Exception &e) {
//		DestroyWindow(pcc->m_hwndMain);
        pcc->CloseWindows();
        e.Report();
        delete pcc;
    }
}
示例#8
0
static void lookAtEntity(ClientConnection& con, const std::string & eid,
                                                const std::string & loc)
{
    Look l;
    l->setFrom(con.getCharacterId());
    Anonymous lookEnt;
    lookEnt->setId(eid);
    l->setArgs1(lookEnt);
    int serial = con.send(l);
    
    verbose( std::cout << "Waiting for In-game look response on connection "
                       << con.getAccount() << std::endl << std::flush; );
示例#9
0
int main (int argc, char *argv[])
{
  if (enet_initialize () != 0)
  {
    fprintf (stderr, "An error occurred while initializing ENet.\n");
    return EXIT_FAILURE;
  }

  if (argc < 4)
  {
    return EXIT_FAILURE;
  }
  
  ClientConnection cc;

  if (!cc.connect(argv[1], atoi(argv[2]), argv[3]))
  {
    return 0;
  }
    
  //noecho();
  //curs_set(FALSE);
    
  EcEventContext ec = ece_context_new ();
  ecsignal_init (ec);
  
  EcEventQueue queue = ece_list_create (ec, NULL);
  
  ece_list_add (queue, STDIN_FILENO, ENTC_EVENTTYPE_READ, NULL);
  
  int res = ENTC_EVENT_TIMEOUT;
  
  while (res != ENTC_EVENT_ABORT)
  {
    switch (res)
    {
      case STDIN_FILENO:
      {
        cc.handleKeys();
      }
      break;
    }
    
    res = ece_list_wait (queue, 10000, NULL);
  }
  
  ecsignal_done ();

  ece_context_delete(&ec);
    
  return 0;
}
void VNCviewerApp32::NewConnection(bool Is_Listening) {
	ClientConnection *pcc = new ClientConnection(this);
	try {
		memcpy((char*)&pcc->m_opts,(char*)&m_options,sizeof(m_options));
		pcc->m_Is_Listening=Is_Listening;
		pcc->Run();
	} catch (Exception &e) {
//		DestroyWindow(pcc->m_hwndMain);
		pcc->CloseWindows();
		e.Report();	
		delete pcc;
	} 
}
示例#11
0
void Server::incomingConnection(qintptr socketDescriptor) {
    logger->writeLog("New connection");
    thread = new QThread();
    ClientConnection *connection = new ClientConnection(socketDescriptor);
    connection->moveToThread(thread);
    connect(thread, SIGNAL(started()), connection, SLOT(run()));

    connect(connection, SIGNAL (compliteScan()), thread, SLOT (quit()));
    connect(connection, SIGNAL (compliteScan()), connection, SLOT (deleteLater()));
    connect(thread, SIGNAL (finished()), thread, SLOT (deleteLater()));

    thread->start();
    qDebug() << "New connection";
}
int main()
{
    ClientConnection * cc = new ClientConnection();
    delete cc;

    // Try all the method calls when not connected
    cc = new ClientConnection();

    cc->login("username", "password");
    cc->create("player", "username", "password");
    cc->wait();

    {
        Atlas::Objects::Operation::RootOperation op;
        cc->send(op);
    }

    cc->pop();
    cc->pending();
    
    delete cc;

    TestClientConnection * tcc = new TestClientConnection();

    {
        Atlas::Objects::Root obj;
        Atlas::Objects::Operation::RootOperation op;
        tcc->test_operation(op);
        tcc->test_errorArrived(op);
        tcc->test_infoArrived(op);
        tcc->test_objectArrived(op);

        Anonymous op_arg;
        op->setArgs1(op_arg);
        tcc->test_infoArrived(op);

        op->setFrom("1");
        tcc->test_infoArrived(op);

        op->setParents(std::list<std::string>());
        tcc->test_operation(op);
        tcc->test_objectArrived(op);

        Info i;
        tcc->test_objectArrived(i);

        Error e;
        tcc->test_objectArrived(e);

        tcc->test_objectArrived(obj);
        obj->setParents(std::list<std::string>());
        tcc->test_objectArrived(obj);

        
    }

    return 0;
}
示例#13
0
void ManagerTimer::timer_callback(unsigned int)
{
	ClientConnection* client;

	// 从客户端管理对象弹出所有延迟待处理的客户端连接对象
	// 并传递给服务端,如果传递失败,则再次置入客户端管理
	// 对象,由下次定时器再次尝试处理

	logger("total client: %d, total server: %d",
		(int) ClientManager::get_instance().length(),
		(int) ServerManager::get_instance().length());

	while (true)
	{
		client = ClientManager::get_instance().pop();
		if (client == NULL)
			break;

		if (transfer(client) == true)
		{
			ClientManager::get_instance().del(client);
			delete client;
			continue;
		}

		// 如果在规定的时间内依然没有服务端准备接收连接,
		// 则直接删除该对象
		if (client->expired())
		{
			logger_error("no server side, client(%s) expired!",
				client->get_peer());
			delete client;
		}
		else
		{
			logger_warn("set client(%s) into queue",
				client->get_peer());
			ClientManager::get_instance().set(client);
		}
		break;
	}
}
示例#14
0
int _tmain(int argc, _TCHAR* argv[])
{
	Settings::ListenPort(L"31337");
	ConsoleLogger::Init();
	ConsoleLogger::Log(L"Starting client connection...\n");

	ClientConnection *connection = new ClientConnection(L"localhost", Settings::ListenPort());
	
	Command *cmd = new Command();
	cmd->Cmd(ProtocolCommand::COMMAND_HELLO);

	connection->Dialog(cmd);
	
	delete connection;

	char *buff = new char[BUFSIZE];
	
	gets_s(buff, BUFSIZE);

	return 0;
}
示例#15
0
bool TransferNode::disconnect(const ClientConnection &cConn) {
	// switch to client mode
	CloseConnectionPacket *packet = new CloseConnectionPacket();
	PacketBasePtr pPacket(packet);
	PacketBufferPtr pBuf = this->packet_serializer.serialize(pPacket);
	this->sendData(pBuf, cConn.getEndPoint());
	if (this->disconnected.tryWait(5000)) {
		return true;
	} else {
		return false;
	}
}
示例#16
0
void
GameServer::OnAcquireTableAccess(AcquireTableAccessPacket* p, void* pParam){
	if( p->m_nSessionId != 0 || p->m_nSessionIdAcquire == 0 || p->m_nTableId <= 0 || p->m_nTournamentId < 0 )
		return;

	ClientConnection*	pConn		= (ClientConnection*)pParam;
	Session*			pSess		= Session::GetSessionById(p->m_nSessionIdAcquire, true);
	bool				bSuccess	= false;
	if( pConn->IsTableConnection() )
		return;

	if( pSess && pSess->IsActive() ){
		int	 nUserId = pSess->GetUserId();
		pSess->SetTableConnection(p->m_nTableId, p->m_nTournamentId, pConn, true);
		pConn->SetTableConnection(p->m_nTableId, p->m_nTournamentId);

		if( nUserId > 0 )
			pConn->SetAuthorized(true);

		p->m_bAvatarIsBlocked	= pSess->IsAvatarBlocked();
		p->m_bChatIsBlocked		= pSess->IsChatBlocked();
		p->m_nUserId			= nUserId;
		bSuccess				= true;
		SafePointer::Release(pSess);
		}

	// Send reply.
	if( bSuccess ){
		//pConn->SetAuthorized(
		pConn->SetSession(pSess);
		p->m_nErrorCode = ES_ERROR_SUCCESS;
		}
	else{
		p->m_nUserId	= 0;
		p->m_nErrorCode = ES_ERROR_UNKNOWN;
		}
	SendPacket(pConn, p, true);
	}
void Ihm::server_newConnection(const ClientConnection&cC)
{
    qDebug() << QThread::currentThreadId() << Q_FUNC_INFO;

    connect(ui->killAllComPushButton, SIGNAL(clicked()), &cC, SLOT(close()));

    connect(&cC, SIGNAL(sig_isAReader(Reader)), this, SLOT(lecteurActif(Reader))); //lecteur connecté
    connect(&cC, SIGNAL(sig_isNotAReader(QString)), SLOT(lecteurInconnu(QString))); //lecteur (ou autre chose) inconnu
    connect(&cC, SIGNAL(sig_dataRead(QString)), SLOT(traitementTrame(QString)));    //données
    connect(&cC, SIGNAL(sig_closed()), SLOT(slot_closed()));  //débranché
    connect(&cC, SIGNAL(destroyed()), SLOT(slot_destroyed()));

    cC.connect(this, SIGNAL(sig_closeConnection()), SLOT(close()));
}
示例#18
0
bool
GameServer::DispatchReceivedData(SocketContext* pSockConn, BYTE* pData, DWORD dwSize, bool bIsFirstData){
	ASSERT(m_pPacketHandler && pData && dwSize > 0);
	if( !pData || !dwSize )
		return false;
	ClientConnection* pConn = (ClientConnection*)pSockConn->GetParam();

	GrowableMemory mem(0, 0, false);
	mem.SetReadonlyBuffer(pData, dwSize);
	if( !pConn )
		return false;

	BasePacket	basePacket;
	int			nOffset				= 0;
	int			nBufferSize			= dwSize;
	int			nSerializedBytes	= 0;

	while( TRUE ){
		if( basePacket.Deserialize(&mem) ){ // Success
			// Handshake must be the only one command accepted while session is not created. 
			if( (basePacket.m_nCode != PacketCodes::_HandShake && basePacket.m_nCode != PacketCodes::_AcquireTableAccess) && pConn->GetSession(false) == NULL ) 
				return false;
			BasePacket* packet	= m_pPacketHandler->CreatePacketByCode(basePacket.m_nCode);
			ASSERT( packet );

#ifndef _DEBUG
		if( packet == NULL )
			return false;
#endif
			// Deserialize received data into known packet.
			if( !mem.SetCurrentOffset(nOffset) )
				return false;
			if( !packet->Deserialize(&mem) )
				return false;

			// Handle received packet.
			OnPacketReceived(pConn, packet);
			delete packet;
		
			nOffset	= mem.GetCurrentOffset();
			if( nOffset == nBufferSize )
				break;
			}
		else
			break;
		}

	return true;
	}
示例#19
0
bool
GameServer::DestroyClientConnection(SOCKET sock, DWORD dwErrorCode){
	if( !sock ) return false;
	bool bRet = true;
	m_lockConnections.Lock(); // Lock
	int nIndex = m_arrAcceptedSocks.FindValue((void*)sock);
	if( nIndex != -1 ){
		ClientConnection* pConn = (ClientConnection*)m_arrAcceptedSocks.GetData(nIndex);
		if( !pConn ) {
			m_arrAcceptedSocks.Delete(nIndex);		// Remove socket from list.
			m_lockConnections.Unlock();				// Unlock
			return true;
			}

		bool bTableConn = pConn->IsTableConnection();
		// Set disconnected state.
		Session* pSess = pConn->GetSession(true);
		pConn->SetConnected(false); 
		OnDisconnected(pConn, dwErrorCode);

		if( pSess ){
			// Make session connectionless.
			if( bTableConn )
				pSess->SetTableConnection(pConn->GetTableId(), pConn->GetTournamentId(), NULL, true);
			else
				pSess->SetConnection(NULL, true);	
			// Release session pointer.
			SafePointer::Release(pSess);
			}

		// Release pointer.
		SafePointer::Release(pConn);				
		// Destroy session.
		if( !bTableConn )
			Session::DestroySession(pSess);
		// Remove conection info.
		m_arrAcceptedSocks.Delete(nIndex);		
		}
	else
		bRet = false;
	m_lockConnections.Unlock();		// Unlock
	return bRet;
	}
/** 
 * @brief pool select
 * @return void
 */
void SelPool::Select()
{
    printf("Selecting in server and %d clients...\n", clients.size());

    FD_ZERO(&read_set);
    FD_ZERO(&write_set);
    FD_SET(listenfd, &read_set);
    vector<ClientConnection*>::iterator it = clients.begin();
    while ( it != clients.end() )
    {
        ClientConnection *client = *it;
        int connFd = client->getFd();

        if( client->isEmpty() && client->isReadable())
        {
            printf("put %d to read_set\n", connFd);
            FD_SET(connFd, &read_set);
        }
        if( client->isWritable() ) /* state == Writing_Response */
        {
            printf("put %d to write_set\n", connFd);
            FD_SET(connFd, &write_set);
            /* if it is CGI request, put its CGI_out pipe to read set */
            if (client->getRequest()->isCGIRequest()) {
                int CGIout = client->getResponse()->getCGIout();
                if (CGIout > maxfd) {
                    maxfd = CGIout;
                }
                FD_SET(CGIout, &read_set);
            }
        }
        it++;
    }

    nready = select(maxfd + 1, &read_set, &write_set, NULL, NULL);
    //printf("Select Finished\n");
}
示例#21
0
void GenericMediaServer::ClientConnection::incomingRequestHandler(void* instance, int /*mask*/) {
  ClientConnection* connection = (ClientConnection*)instance;
  connection->incomingRequestHandler();
}
示例#22
0
void ServerCore::Serve()
{
    fd_set sockets;
    struct timeval timeout;
    int max_desc;
    int readsocks;

    while(mRunning) {
        /* Build select list */
        FD_ZERO(&sockets);
        FD_SET(mListener, &sockets);
        max_desc = mListener;
        sem_wait(&mMutex);
        map<unsigned int, ClientConnection*>::iterator it = mClientMap.begin();
        while(it != mClientMap.end())
        {
            int fd = (*it).second->getFd();
            FD_SET(fd, &sockets);
            if (fd>max_desc) {
                max_desc = fd;
            }
            it++;
        }
        sem_post(&mMutex);

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;
        readsocks = select(max_desc+1, &sockets, (fd_set*)0, (fd_set*)0,
                           &timeout);

		if (readsocks < 0) {
			printf("ERROR: select failed");
			break;
		}

        if(readsocks) {
            if(FD_ISSET(mListener, &sockets)) {
                /* New connection */
                int conn = accept(mListener, NULL, NULL);
                if (mClientMap.size()<MAX_CLIENTS) {
                    ClientConnection* client = new ClientConnection(conn);
                    mClientMap[mClientCount++] = client;
                } else {
                    close(conn);
                }
            }

            sem_wait(&mMutex);
            it = mClientMap.begin();
            while(it != mClientMap.end())
            {
                ClientConnection* client = (*it).second;
                if (FD_ISSET(client->getFd(), &sockets)) {
                    string data;
                    int status = client->Read(data);
                    if (status<0) {
                        /* Error , close */
                        map<unsigned int, ClientConnection*>::iterator it2 = it;
                        it2++;
                        delete client;
                        close(client->getFd());
                        mClientMap.erase(it);
                        it = it2;
                        continue;
                    }
                    if (status>0) {
                        if (mDispatch) {
                            /* Release the mutex so dispatched calls
                             * can write back to socket.
                             * This is safe, since this is the only thread
                             * that actually modifies the client connection map
                             */
                            sem_post(&mMutex);
                            mDispatch((*it).first,data);
                            sem_wait(&mMutex);
                        }
                    }
                }
                it++;
            }
            sem_post(&mMutex);
        } 
    }
}
示例#23
0
void Commander::dispatch(const RootOperation& op)
{
    Appearance appear = smart_dynamic_cast<Appearance>(op);
    if (appear.isValid()) {
        assert(op->hasAttr("for"));
        Agent* ag = m_server->findAgentForEntity(op->getAttr("for").asString());
        if (ag) {
            ag->setEntityVisible(op->getTo(), true);
        } else {
            // doesn't exist yet, mark as visible if / when the agent is created
            Agent::setEntityVisibleForFutureAgent(op->getTo(), op->getAttr("for").asString());
        }
    }
    
    Disappearance disap = smart_dynamic_cast<Disappearance>(op);
    if (disap.isValid()) {
        assert(op->hasAttr("for"));
        Agent* ag = m_server->findAgentForEntity(op->getAttr("for").asString());
        if (ag) ag->setEntityVisible(op->getTo(), false);
    }
    
    Create cr = smart_dynamic_cast<Create>(op);
    if (cr.isValid()) {
        std::vector<Root> args(op->getArgs());
        assert(!args.empty());
        RootEntity ent = smart_dynamic_cast<RootEntity>(args.front());
        assert(ent.isValid());
        
        static int idCounter = 900;
        char buf[32];
        snprintf(buf, 32, "_created_%d", ++idCounter);
        std::string id(buf);
        
        ent->setId(id);
        std::string loc = ent->getLoc();
        assert(m_server->m_world.count(loc));
        
        StringList children(m_server->m_world[loc]->getContains());
        children.push_back(id);
        m_server->m_world[loc]->setContains(children);

        m_server->m_world[id] = ent;
        
        Create bcr(cr);
        bcr->setArgs1(ent);
        Agent::broadcastSight(bcr);
    }
    
    Delete del = smart_dynamic_cast<Delete>(op);
    if (del.isValid()) {
        std::vector<Root> args(op->getArgs());
        assert(!args.empty());
        
        std::string id = args.front()->getId();
        assert(m_server->m_world.count(id));
        m_server->m_world.erase(id);
        
        Agent::broadcastSight(op);
    }
    
    Move mv = smart_dynamic_cast<Move>(op);
    if (mv.isValid()) {
        RootEntity ent = m_server->getEntity(op->getTo());
        
        std::vector<Root> args(op->getArgs());
        
        if (args.front()->hasAttr("loc")) {
            std::string newLocId = args.front()->getAttr("loc").asString();
            
            RootEntity oldLoc = m_server->getEntity(ent->getLoc()),
                newLoc = m_server->getEntity(newLocId);
            
            ent->setLoc(newLocId);
            // modify stamps?
            oldLoc->modifyContains().remove(ent->getId());
            newLoc->modifyContains().push_back(ent->getId());
        }
        
        if (args.front()->hasAttr("pos"))
            ent->setPosAsList(args.front()->getAttr("pos").asList());
            
        // handle velocity changes
        Agent::broadcastSight(op);
        return;
    }
    
    Sound snd = smart_dynamic_cast<Sound>(op);
    if (snd.isValid()) {
        
        std::vector<Root> args(op->getArgs());
        assert(!args.empty());
        
        if (snd->hasAttr("broadcast")) {
            Agent::broadcastSound(smart_dynamic_cast<RootOperation>(args.front()));
        }
    }
    
    Sight st = smart_dynamic_cast<Sight>(op);
    if (st.isValid()) {
        if (st->hasAttr("broadcast")) {
            std::vector<Root> args(op->getArgs());
            assert(!args.empty());
            Agent::broadcastSight(smart_dynamic_cast<RootOperation>(args.front()));
        }
    }
    
    Set s = smart_dynamic_cast<Set>(op);
    if (s.isValid()) {
        
        std::vector<Root> args(op->getArgs());
        for (unsigned int A=0; A < args.size(); ++A) {
            std::string eid = args[A]->getId();
        
            RootEntity entity = m_server->getEntity(eid);
            Root::const_iterator I = args[A]->begin();
            
            for (; I != args[A]->end(); ++I) {
                if ((I->first == "id") || (I->first == "parents") || (I->first == "objtype")) {
                    continue;
                }
                
                assert(I->first != "loc");
                entity->setAttr(I->first, I->second);
            }
        }

        Agent::broadcastSight(s);
    }
    
    Action act = smart_dynamic_cast<Action>(op);
    if (act.isValid()) {
        std::vector<Root> args(op->getArgs());
        
        if (act->getParents().front() == "command") {
            std::string cid = args[0]->getAttr("cid").asString();
            
            if (cid == "socket-shutdown") {
                std::string acc = args[0]->getAttr("acc").asString();
                ClientConnection* cc = m_server->getConnectionForAccount(acc);
                assert(cc);
                cc->shutdown();
            } else if (cid == "add-many-objects") {
                m_server->addManyObjects(args[0]->getAttr("acc").asString());
            } else if (cid == "set-world-time") {
                /* double t = */ args[0]->getAttr("seconds").asFloat();
                
            } else {
                std::cerr << "unknown command " << cid << std::endl;
            }
        } // of command action case
    } // of action case
}
示例#24
0
void GenericMediaServer::ClientConnection::incomingRequestHandler(void* instance, int /*mask*/) { 	//envir().taskScheduler() 的回调,用于处理client请求
  ClientConnection* connection = (ClientConnection*)instance;
  connection->incomingRequestHandler();		//负责对 rtsp 客户端的请求处理
}
示例#25
0
void* HandleConnectionProc( void* v )
{
	// The socket for the client
	ICommunicator*	pComm = (ICommunicator*)(v);

	// We just opened a new connection, we should do some handshaking
	if( pComm->IsConnectionOpen() )
	{
		ClientConnection*	pConnection = new ClientConnection( pComm );
		GlobalLog()->PrintNew( pConnection, __FILE__, __LINE__, "client connection" );

		if( !pConnection->PerformHandshaking( secret_code ) ) {
			GlobalLog()->PrintEasyError( "Failed to handshake with client, abandoning" );
		}
				
		// We should first give the client an opportunity to 
		// identify itself.  

		//
		// We have three different types of clients:
		// - worker client, purely a worker
		// - job submission client, a client that submits jobs
		// - master control program (MCP) client, in which case the server responds to 
		//   all kinds of queries from this kind of client
		//
		CLIENT_TYPE ctype = pConnection->GetClientType();

		switch( ctype )
		{
		case eClient_Worker:
//			GlobalLog()->PrintEasyEvent( "Talking to worker client" );
			pConnection->release();
			pConnection = new WorkerClientConnection( pComm );
			GlobalLog()->PrintNew( pConnection, __FILE__, __LINE__, "worker client connection" );
			break;

		case eClient_Submitter:
			GlobalLog()->PrintEasyEvent( "Talking to job submission client" );
			pConnection->release();
			pConnection = new SubmitterClientConnection( pComm );
			GlobalLog()->PrintNew( pConnection, __FILE__, __LINE__, "submitter client connection" );
			break;

		case eClient_MCP:
			GlobalLog()->PrintEasyEvent( "Talking to master control program" );
			pConnection->release();
			pConnection = new MCPClientConnection( pComm );
			GlobalLog()->PrintNew( pConnection, __FILE__, __LINE__, "MCP client connection" );
			break;

		default:
			GlobalLog()->PrintEasyEvent( "Unknown client type" );
			break;
		}

		// Now just sit back and let each of the client types do their thing
		pConnection->PerformClientTasks();
		pConnection->release();

	} else {
		GlobalLog()->PrintEasyError( "Broken connection to client, terminiating session" );
	}

	pComm->release();
	return 0;
}
/** @brief check select pool and process client reqeusts
 *
 *  @param pool select pool
 *  @return void
 */
void SelPool::check_clients() 
{
    int connfd;

    vector<ClientConnection*>::iterator it = clients.begin();
    while ( it != clients.end() )
    {
        ClientConnection *client = *it;
        connfd = client->getFd();
        printf("Handling %d\n", connfd);

        /* Client Connection State Machine */
        switch ( client->getState() )
        {
            case ClientConnection::Ready_ForRead:
            {
                printf("Client State: Ready_ForRead\n");
                /* read ready client socket */
                if (FD_ISSET(connfd, &read_set))
                {
                    readHandler(client);
                    if (client->getState() == ClientConnection::Request_Parsed)
                    {
                        processHandler(client);
                        /* if the client is closed after processing */
                        if (client->getState() == ClientConnection::Closed)
                        {
                            Socket::Close_Socket(connfd);
                            FD_CLR(connfd, &read_set);
                            delete client;
                            clients.erase(it);
                            continue;
                        }
                        writeHandler(client);
                    }
                }
                break;
            }

            case ClientConnection::Request_Parsed: {
                printf("Client State: Request_Parsed\n");
                break;
            }

            case ClientConnection::Writing_Response: 
            {
                printf("Client State: Writing_Response\n");
                if (FD_ISSET(connfd, &write_set)) 
                {
                    if (!client->getRequest()->isCGIRequest())
                    {
                        processHandler(client);
                        writeHandler(client);
                    }
                    else if (FD_ISSET(client->getResponse()->getCGIout(), &read_set))
                    {
                        /* CGI request : if CGIout is also ready for reading */
                        pipeHandler(client);
                        writeHandler(client);
                    }
                }
                break;
            }

            case ClientConnection::Done_Response: {
                printf("Client State: Done_Response\n");
                break;
            }

            default: {
                break;
            }
        }
        it++;
    }
}