Search code examples
csocketsserversocketsocketserverlocalserversocket

Need Clarification in the socket server while loop


Below is a part of code from my socket server. I am not clear about some steps so I have some questions. My questions are below:

  1. Why I need to use while (1)?
  2. What is the purpose of exit (-1), will it close my socket?
  3. Why the data_len is initialized as 1?
  4. If the server runs and there is no data from the client side, then what will happen to the server? Will it get closed?

Actually, I need a detail explanation for the below part of the code.

while(1) {
    if ((new = accept(sock, (struct sockaddr*)&client, &sockaddr_len)) == ERROR) {
        perror ("accept");
    exit (-1);

    }

    printf("New client connected from port no %d and IP %s\n",ntohs(client.sin_port), inet_ntoa(client.sin_addr));
data_len = 1;
while (data_len) {
    data_len = recv (new, data, MAX_DATA, 0);
    if (data_len) {
        send (new, data, data_len, 0);
    data [data_len]='\0';
    printf("Sent mesg: %s", data);
    }
}
printf("Client Disconnected\n");
close(new);
}
close (sock);

Solution

  • If you want to accept new connections after you're done with the first one, you need to do the same code over again to accept and handle the new connection. The easiest way to do it is by using a loop of some kind.

    The exit function simply exits your process. Typically this will close all open sockets as well as release all other open/allocated resources. The function does not return.

    If you don't initialize the data_len variable, its value will be indeterminate and using it will lead to undefined behavior. At least if the variable is a local non-static variable.

    If there is no data from the client, the recv call will block indefinitely.