BSD Sockets Interface Programmer's Guide

170 Chapter 8
Programming Hints
Adding a Server Process to the Internet Daemon
* M A I N
*
* This is the actual server routine that the /etc/inetd forks to
* handle each individual connection. Its purpose is to receive
* the request packets from the remote client, process them,
* and return the results to the client.
*
*/
main()
{
char buf[10]; /* This example uses 10 byte messages. */
int len, lenl;
/* Go into a loop, receiving requests from the remote
* client. After the client has sent the last request,
* it will do a shutdown for sending, which will cause
* an end-of-file condition to appear on this end of the
* connection. After all the client's requests have
* been received, the next recv call will return zero
* bytes, signaling an end-of-file condition. This is
* how the server will know that no more requests will
* follow, and the loop will be exited.
*/
while (len = recv(0, buf, 10, 0)) {
if (len == -1) {
exit (1); /* error from recv */
}
/* The reason this while loop exists is that there
* is a remote possibility of the above recv returning
* less than 10 bytes. This is because a recv returns
* as soon as there is some data, and will not wait for
* all of the requested data to arrive. Since 10 bytes
* is relatively small compared to the allowed TCP
* packet sizes, a partial receive is unlikely. If
* this example had used 2048 bytes requests instead,
* a partial receive would be far more likely.
* This loop will keep receiving until all 10 bytes
* have been received, thus guaranteeing that the
* next recv at the top of the loop will start at the
* beginning of the next request.
*/
while (len < 10) {
len1 = recv(0, &buf[len], 10-len, 0);
if (len1 == -1) {
exit (1);
}
len += len1;
}
/* This sleep simulates the processing of
* the request that a real server may do.
*/
sleep(1);
/* Send a response back to the client. */
if (send(0, buf, 10, 0) != 10) {
exit (1);
}
}
}
/* The loop has terminated, because there are no
* more requests to be serviced.