Пример #1
0
//called by the connection handler
void CClientsHandler::AddClient(CClient* client)
{
	CLock lock(m_mutex);
    
    Log("AddClient");
    
	if (m_clients.size() >= FD_SETSIZE) //maximum number of clients reached
	{
		LogError("number of clients reached maximum %i", FD_SETSIZE);
		CTcpData data;
		data.SetData("full\n");
		client->m_socket.Write(data);
		delete client;
		return;
	}

	//assign lights and put the pointer in the clients vector
	client->m_lights = m_lights;
	m_clients.push_back(client);
}
Пример #2
0
//this is called from a loop from main()
void CClientsHandler::Process()
{
       
    //Open listening unix socket if it's not already
    if (!m_socket.IsOpen())
    {
        Log("opening listening TcpSocket on %s:%i",m_address.empty() ? "*" : m_address.c_str(), m_port);
        if (!m_socket.Open(m_address, m_port,1000000))
        {
	        LogError("%s", m_socket.GetError().c_str());
	        m_socket.Close();
        }
    }
    
	//see if there's a socket we can read from
	vector<int> sockets;
	GetReadableFd(sockets);

	for (vector<int>::iterator it = sockets.begin(); it != sockets.end(); ++it)
	{
		int sock = *it;
		int returnv;
		
		if (sock == m_socket.GetSock()) //we can read from the listening socket
		{
			CClient* client = new CClient;

			returnv = m_socket.Accept(client->m_socket);

			if (returnv == SUCCESS)
			{
				Log("%s:%i connected",client->m_socket.GetAddress().c_str(), client->m_socket.GetPort());
				AddClient(client);
			}
			else
			{
				delete client;
				Log("%s", m_socket.GetError().c_str());
			}
		}
		else
		{
			//get the client the sock fd belongs to
			CClient* client = GetClientFromSock(sock);
			if (client == NULL) //guess it belongs to nobody
				continue;

			//try to read data from the client
			CTcpData data;
			int returnv = client->m_socket.Read(data);
			if (returnv == FAIL)
			{ //socket broke probably
				Log("%s", client->m_socket.GetError().c_str());
				RemoveClient(client);
				continue;
			}
            
			//add data to the messagequeue
			client->m_messagequeue.AddData(data.GetData(), data.GetSize());

			//check messages from the messaqueue and parse them, if it fails remove the client
			if (!HandleMessages(client))
				RemoveClient(client);
		}
	}
}