Varie correzioni, completata revisione capitolo sull'I/O su file
[gapil.git] / listati / ClientEcho.c
1 void ClientEcho(FILE * filein, int socket) 
2 {
3     char sendbuff[MAXLINE+1], recvbuff[MAXLINE+1];
4     int nread, nwrite; 
5     int maxfd;
6     fd_set fset;
7     int eof = 0;
8     /* initialize file descriptor set */
9     FD_ZERO(&fset);
10     maxfd = max(fileno(filein), socket) + 1;
11     while (1) {
12         FD_SET(socket, &fset);         /* set for the socket */
13         if (eof == 0) {
14             FD_SET(fileno(filein), &fset); /* set for the standard input */
15         }
16         select(maxfd, &fset, NULL, NULL, NULL); /* wait for read ready */
17         if (FD_ISSET(fileno(filein), &fset)) {  /* if ready on stdin */
18             if (fgets(sendbuff, MAXLINE, filein) == NULL) { /* if no input */
19                 eof = 1;               /* EOF on input */
20                 shutdown(socket, SHUT_WR);      /* close write half */
21                 FD_CLR(fileno(filein), &fset);  /* no more interest on stdin */
22             } else {                   /* else we have to write to socket */
23                 nwrite = FullWrite(socket, sendbuff, strlen(sendbuff)); 
24                 if (nwrite < 0) {      /* on error stop */
25                     printf("Errore in scrittura: %s", strerror(errno));
26                     return;
27                 }
28             }
29         }
30         if (FD_ISSET(socket, &fset)) { /* if ready on socket */ 
31             nread = read(socket, recvbuff, strlen(sendbuff)); /* do read */
32             if (nread < 0) {  /* error condition, stop client */
33                 printf("Errore in lettura: %s\n", strerror(errno));
34                 return;
35             }
36             if (nread == 0) { /* server closed connection, stop */
37                 if (eof == 1) {
38                     return;
39                 } else {
40                     printf("EOF prematuro sul socket\n");
41                     return;
42                 }
43             }
44             recvbuff[nread] = 0;   /* else read is ok, write on stdout */
45             if (fputs(recvbuff, stdout) == EOF) {
46                 perror("Errore in scrittura su terminale");
47                 return;
48             }
49         }
50     }
51 }