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:
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);
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.