I am using class Client
class Client
{
Client(sf::TcpSocket *_socket);
sf::TcpSocket *socket;
};
Constructor:
Client::Client(sf::TcpSocket *_socket)
{
socket=_socket;
}
In the thread, my listener is waiting for clients to connect and add them to a vector of clients.
while(isAcceptingConnections==true)
{
sf::TcpSocket *socket=new sf::TcpSocket;
if (listener.accept(*socket) == sf::Socket::Done)
{
socket->setBlocking(false);
Client client(socket);
clients.push_back(client);
}
else
delete socket;
}
As you see I am dynamically allocating memory for each new connection and using a pointer to each socket as an argument for Client constructor. I would like to be able to free this memory through Client object once the connection is disabled. How can I do it? In a different thread, I have packet transfer which receives and sends in loop packets to each client. I tried using "delete clients[i].socket" but it crashes the server. Any idea?
What I am trying to do is to be able to free memory once the socket is no more used by the client.
for(unsigned int i=0;i<clients.size();i++)
{
if(!clients[i].socket->send(heartbeat))
{
clients[i].socket->disconnect();
delete clients[i].socket;
clients.erase(clients.begin()+i,clients.begin()+i+1);
}
}
or
for(unsigned int i=0;i<clients.size();i++)
{
if(!clients[i].socket->send(heartbeat))
{
clients.erase(clients.begin()+i,clients.begin()+i+1);
}
}
~Client()
{
client.socket->disconnect();
delete client.socket;
}
Both options are crashing my server though. How should I do it?