Server:
bool CTCPServer::ServerLoop()
{
bool ret = false;
m_online = true;
sf::SelectorTCP * serverSelector = (sf::SelectorTCP*)m_selector;
sf::SocketTCP * serverSocket = (sf::SocketTCP*)(m_socket);
if(serverSelector && serverSocket)
{
// Add the listener
serverSelector->Add(*serverSocket);
while(m_online)
{
// Get the sockets ready for reading
unsigned int NbSockets = serverSelector->Wait();
// We can read from each returned socket
for (unsigned int i = 0; i < NbSockets; ++i)
{
// Get the current socket
sf::SocketTCP socket = serverSelector->GetSocketReady(i);
if (socket == *serverSocket)
{
if(m_clients.size() < TCP_MAX_CLIENTS)
{
// If the listening socket is ready, it means that we can accept a new connection
sf::IPAddress *address = new sf::IPAddress;
sf::SocketTCP *client = new sf::SocketTCP;
serverSocket->Accept(*client, address);
// Add it to the selector
serverSelector->Add(*client);
// Add it to our internal list
AddClient(address, client);
}
else
{
PrintLog(TCP_EVENT, "Client limit(%d) reached", TCP_MAX_CLIENTS);
}
}
else
{
// Else, it is a client socket so we can read the data he sent
char buffer[TCP_MAX_SIZE] = "";
size_t recievedSize = 0;
if (socket.Receive(buffer, TCP_MAX_SIZE, recievedSize) == sf::Socket::Done)
{
size_t clientId = GetClientId(&socket);
if(clientId < TCP_MAX_CLIENTS)
{
if(HandleInternalMessage(clientId, buffer, recievedSize) == false ||
(m_forwardInternalMessage == true))
{
// This is not a internal message, push it forward to callback function.
(*TCPServerClientRecieveCallback)(clientId, buffer, recievedSize);
}
}
}
else
{
// Error : we'd better remove the socket from the selector
RemoveClient(GetClientId(&socket), DISCONNECT_SHUTDOWN);
}
}
}
}
}
else
{
PrintLog(TCP_ERROR, "%s Memory error", AT);
}
serverSocket->Close();
return ret;
}
Client:
void CTCPClient::ListenLoop()
{
sf::SocketTCP * socket = (sf::SocketTCP*)(m_socket);
if(socket)
{
char buffer[TCP_MAX_SIZE] = "";
size_t recievedSize = 0;
while(m_online)
{
if(socket->Receive(buffer, TCP_MAX_SIZE, recievedSize) == sf::Socket::Done)
{
if(HandleInternalMessage(buffer, recievedSize) == false ||
(m_forwardInternalMessage == true))
{
(*TCPClientServerResponse)(buffer, recievedSize);
}
}
else
{
PrintLog(TCP_EVENT, "Closing down connection with server");
m_online = false;
}
}
}
socket->Close();
}