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:
- Why I need to use while (1)?
- What is the purpose of exit (-1), will it close my socket?
- Why the data_len is initialized as 1?
- 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);