I am able to start a server and receive data from client. I am running in a loop to get data from socket receive buffer and all is working fine until client closes socket, I am not able to handle this.
I am reading data from the client using the following line:
When a client disconnects, it crashes when calling this function.
Any tips on how to avoid crash when client disconnects? Is there a way of checking for client connection before trying to read from it?
Make sure to call ConnectionSocket->HasPendingData(DatagramSize) before, this function will return if data is there, if not your socket is disconnected. It is typically called like the following pseudo code:
while (sock->HasPendingData(...))
{
if (Socket->RecvFrom(...))
{
// handle incoming data
}
}
But what if a client is connected, but haven’t written data, then sock->HasPendingData(…) returns false although the client might still be connected.
What I was opting for was to use sock->RecvFrom to block until the specified amount of bytes were read, or the socket closed, hence using the WaitAll flag.
In the documentation this flag should wait until the data was read, or the socket close.
Thanks, but does not seem to work. I always seem to crash either way, using this code :
while(shouldReceiveData == true){
if (Socket->GetConnectionState() != SCS_Connected){
// Socket disconnected, remove from list of connected sockets?
}else{
aSocket->Recv(Data, MaxBuffer, BytesRead);
}
}
I stopped using the WaitAll flag btw. It works fine until I disconnect the client. Any tips on how to handle the general case of a client disconnecting?