asawilliams
asawilliams

Reputation: 2948

c++ winsock2, how to tell when a connection closes

I have a c++ program using winsock2. I would like to know how to tell when someone's connection to my program closes.

Upvotes: 3

Views: 1078

Answers (2)

Andres Peralta
Andres Peralta

Reputation: 51

int received_bytes = recv(_socket, buffer, sizeof(buffer)-1,0);
if(received_bytes > 0)
{
   //data received
}
else if (received_bytes == 0)
{
  //connection closed
}

else
{
  //wait for more data
}

Upvotes: 0

Martin v. Löwis
Martin v. Löwis

Reputation: 127537

Use select to wait for reading on the socket; when the socket is closed winsock should report it as readable. Receiving from the socket will then give you 0 bytes, telling you that the socket was closed.

Upvotes: 5

Related Questions