Hello,
I am pretty new to networking and have just read a few tutorials about it and read the SFML documentation and treid to programm a little network-manager.
It's nothing special. One user should be able to be the host and an other one should be allowed to join the "game".
I didn't want to use a seperate server-application, so the user can choose if he wants to host a game and "be" the server.
Therefore I have a network-manager class. It does all the server-stuff(selector and listener). This network-manager is run in a sperate thread, if the user hosts a game and the methode looks like this:
while( true )
{
if( selector_.Wait() )
{
if( selector_.IsReady( listener_ ) )
{
// listener is ready, so there is a pending connection
sf::TcpSocket* client = new sf::TcpSocket;
if( listener_.Accept( *client ) == sf::Socket::Done )
{
clients_.push_back( client );
selector_.Add( *client );
client->SetBlocking( false );
std::cout << "GAME_INFO: Client connected with IP " << client->GetRemoteAddress() << std::endl;
}
}
else
{
// Check whether the other objects are ready
for( std::list<sf::TcpSocket*>::iterator it = clients_.begin();
it != clients_.end(); ++it )
{
sf::TcpSocket client = **it;
if( selector_.IsReady( client ) )
{
sf::Packet packet;
sf::Socket::Status state = client.Receive( packet );
if( state == sf::Socket::Done )
{
handle_message( client, packet );
}
}
}
}
}
}
Basiclly it's taken from the documentation. But now I have a problem. A use may disconnect for any reason. In this case I am not able to remove the socket.
What I tried:
for( std::list<sf::TcpSocket*>::iterator it = clients_.begin();
it != clients_.end();)
{
sf::TcpSocket client = **it;
if( selector_.IsReady( client ) )
{
sf::Packet packet;
sf::Socket::Status state = client.Receive( packet );
if( state == sf::Socket::Done )
{
handle_message( client, packet );
++it;
continue;
}
else if( state == sf::Socket::Disconnected )
{
selector_.Remove( client );
std::cout << "Client disconnected with IP " << client.GetRemoteAddress();
it = clients_.erase( it );
}
}
}
But this is not working. If i put "++it" to the end of the loop, my socket won't receive any messages. Even if the socket is not removed, it will not catch the welcome-message which I send to the clients.
Has anyone already programmed a network-manager with SFML 2 and can give me some hint? Or would you do it in a completly other way?
Thanks for your help,
Fred