Should I close the socket on the server side after the client disconnects?

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

0 is returned). But I still need to call

close(client);

      

?

+3


source to share


3 answers


Yes.

If you are recv()

0 bytes, then the kernel is a way to tell you that the remote host has closed its sending side of the connection. They may still have an open socket and may receive more data that you are sending (but not responding).



When you call close()

on a TCP socket, you do two things:

  • Turning off the local portion of the socket, letting the remote host know that you have also finished transferring. Without it, you could potentially leave clients hanging, waiting for more data to be sent.
  • Closing the file descriptor. This frees an entry in the process's open file table. Without it, you waste resources and may end up out of memory or available file descriptors. In most cases, each operating system has a hard limit on the number of file descriptors (or descriptors) that a process can open at one time.
+8


source


You need to close the handle to release the resources bound to it.



+1


source


The answer is yes. The reason is that accept () allocates memory, close () frees that memory.

Imagine a theoretical situation where your code is in a loop and that every time you call accept () it allocates 1GB of RAM (pretend this is a really inefficient socket library :-)). Whenever you call close (), it frees up 1GB of RAM. If you never call close (), how many times around the loop will it take () before you run out of memory?

Of course accept () only allocates a small chunk of memory, but in the end you run out of memory if you don't do anything.

-1


source







All Articles