So let me simplify the code I'm working on:
int fd = socket(...);
int client = accept(fd, ...);
while (true) {
int bytes_read = recv(client, ...);
if (bytes_read == 0) {
break;
}
};
At this point I already know that the client is disconnected (recv
returned 0). But do I still have to call
close(client);
?
Yes.
When you recv()
0 bytes, that's the kernel's way of letting you know that the remote host has shut down their sending side of the connection. It's possible that they still have the socket open and could receive more data you send (but not reply).
When you call close()
on a TCP socket, you are doing two things:
You need to close the descriptor to release the resources bound to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With