‘str_cli’ Function (Revisited)
Three conditions are handled with the socket:
1.If the peer TCP sends data, the socket becomes readable and read returns greater than 0 (i.e., the number of bytes of data).
2.If the peer TCP sends a FIN (the peer process terminates), the socket becomes readable and read returns 0 (EOF).
3.If the peer TCP sends an RST (the peer host has crashed and rebooted), the socket becomes readable, read returns –1, and errno contains the specific error code.
#include "unp.h"
void str_cli(FILE *fp, int sockfd)
{
int maxfdp1;
fd_set rset;
char sendline[MAXLINE], recvline[MAXLINE];
FD_ZERO(&rset);
for(;;)
{
FD_SET(fileno(fp), &rset);
FD_SET(sockfd, &rset);
maxfdp1=max(fileno(fp), sockfd)+1;
Select(maxfdp1, &rset, NULL, NULL, NULL);
if(FD_ISSET(sockfd, &rset))
{
if(Readline(sockfd, recvline, MAXLINE)==0)
err_quit("str_cli: server terminated prematurely");
Fputs(recvline, stdout);
}
if(FD_ISSET(fileno(fp), &rset))
{
if(Fgets(sendline, MAXLINE, fp)==NULL)
return;
Writen(sockfd,sendline, strlen(sendline));
}
}
}
Implementation of str_cli function using select (improved in Figure 6.13(See 8.4.7)).
Batch Input and Buffering
Unfortunately, our str_cli function is still not correct. First, let’s go back to our original version, Figure 5.5(See 8.3.5). It operates in a stop-and-wait mode, which is fine for interactive use: It sends a line to the server and then waits for the reply. This amount of time is one RTT plus the server’s processing time (which is close to 0 for a simple echo server). We can therefore estimate how long it will take for a given number of lines to be echoed if we know the RTT between the client and server.