/* select.c: select from different input when ready*/ #include #include #include #include #include #include #include #include "tcplib.h" #define PORT 2527 #define BUFLEN 64 int main(int argc, char *argv[]) { int sock; char *host; int maxfdp1, nfound, nread; char buff[BUFSIZ+1]; int size; fd_set readmask; char *prompt = "hello-> "; int n = strlen(prompt); if (argc != 2) { fprintf(stderr,"usage : %s server-name\n", argv[0]); exit(1); } host = argv[1]; sock = socketClient(host, PORT); if (sock <= 0) { fprintf(stderr,"connection failed.\n"); exit(2); } for (; ;) { /* initialize the read mask */ FD_ZERO(&readmask); /* we will be checking standard input (file 0) and the * network (file sock) */ FD_SET(0, &readmask); FD_SET(sock, &readmask); write(1, prompt, n); /* print the prompt to the screen */ maxfdp1 = sock + 1; /* how many file descriptors to check? */ /* system call 'select' to examine how many inputs are ready */ nfound = select(maxfdp1, &readmask, (fd_set *)0, (fd_set*)0, (struct timeval *)0); if (nfound < 0) { exit(3); } /* check the standard input, keyboard for input */ if (FD_ISSET(0, &readmask)) { nread = read(0, buff, BUFSIZ); if (nread < 0) { fprintf(stderr, "read error from keyboard\n"); exit(4); } else if (nread == 0) break; if (write(1, buff, nread) != nread) { fprintf(stderr, "write error to screen\n"); exit(5); } } /* * check to see if socket has data, if so read and pass it to the * local screen. */ if (FD_ISSET(sock, &readmask)) { write(1, "from server : ", strlen("from server : ")); nread = read(sock, &size, sizeof(int)); if (nread <= 0) { fprintf(stderr, "read error from socket 1 bytes read = %d\n", nread); break; } nread = read(sock, buff, size); if (nread <= 0) { fprintf(stderr, "read error from socket 2\n"); break; } buff[nread] = 0; if (write(1, buff, nread) != nread) { fprintf(stderr, "write error in socket\n"); exit(6); } } } // for }