Maybe you could provide code snippets. They would provide more information than the questions in your first post.
Hmm ok. What snippets do you need exactly?
Here is my server-sided "receive packets" function:
void NetworkManager::recPackets()
{
// Receive a message from the client
while(running)
{
// Wait for data on any incoming socket
if(Selector.wait(sf::milliseconds(250)))
{
// Test the listener
if(Selector.isReady(listener))
{
maxConID++;
Connector* newConnector = new Connector;
newConnector->player = NULL;
newConnector->setID(maxConID);
if(listener.accept(newConnector->socket) == sf::Socket::Done)
{
mu::lockMutexes();
mutex.lock();
// Adds a new client to client list
ent::connectors.push_back(newConnector);
// Add a new client to the selector so we will be
// notified if we recieve something from it
Selector.add(newConnector->socket);
mutex.unlock();
mu::unlockMutexes();
}
else
{
// Nothing we can do...
}
}
else
{
// The listener socket is not ready, test all other sockets
for(sf::Int32 i = 0; i < ent::connectors.size(); i++)
{
sf::TcpSocket &client = ent::connectors.at(i)->socket;
if(Selector.isReady(client))
{
// The client has some data, we can recieve it
sf::Packet packet;
if(client.receive(packet) == sf::Socket::Done)
{
sf::Uint32 packetCode;
packet >> packetCode;
mu::lockMutexes();
handlePacket(packetCode, packet, ent::connectors[i]->getID());
mu::unlockMutexes();
}
else if(client.receive(packet) == sf::Socket::Disconnected)
{
mu::lockMutexes();
mutex.lock();
ent::playerHandler.handleDisconnect(ent::connectors[i]->getID());
mutex.unlock();
mu::unlockMutexes();
}
else if(client.receive(packet) == sf::Socket::Error)
{
std::cout << "NetworkingError";
}
}
}
}
}
}
}
The handlePacket() function takes a packet, unloads it, and does something with the data (puts in some movement requests, tile changes, etc).
The mu::lock/unlockMutexes() functions lock all the global mutexes to prevent deadlock and crashes. Yes, it's a pain to do multithreading. I have to lock everything every time a thread accesses some sort of data within the program. I'm beginning to wonder if multi-threading was even worth it.
The thing I don't understand is why it doesn't just freeze up completely (because of deadlock or failing to unlock a mutex)-- it always resumes normal work receiving packets/handling data/saving after about 10-30 seconds (in some bad cases, longer). I also tested to make sure that it didn't have to do with the loading/saving aspects of the program and it seemed to be normally timed. The thing is that it only freezes like this when there are multiple players online (all of them seem to be doing normal tasks in the game-- nothing out of the ordinary that would execute some long function).
If you want to have an extended look at it, you can add me on Skype (brady.welch).