/* p3clientV2.c (sample starting point) */ #include #include #include #include #include #include #include int main() { fd_set readfds; /* add both stdin (fd 0) and the sock to the fd_set */ int sock = socket( PF_INET, SOCK_STREAM, 0 ); if ( sock < 0 ) { perror( "socket() failed" ); return EXIT_FAILURE; } struct sockaddr_in server; struct hostent * hp; server.sin_family = PF_INET; hp = gethostbyname( "localhost" ); if ( hp == NULL ) { perror( "Unknown host" ); return EXIT_FAILURE; } bcopy( (char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length ); int port = 8127; server.sin_port = htons( port ); if ( connect( sock, (struct sockaddr *)&server, sizeof( server ) ) < 0 ) { perror( "connect() failed" ); return EXIT_FAILURE; } while ( 1 ) { FD_ZERO( &readfds ); FD_SET( 0, &readfds ); /* add stdin */ FD_SET( sock, &readfds ); /* BLOCK on select() */ select( FD_SETSIZE, &readfds, NULL, NULL, NULL ); if ( FD_ISSET( 0, &readfds ) ) { char msg[1024]; scanf( "%[^\n]", msg ); /* read everything up to the '\n' */ getchar(); /* read (skip) the '\n' character */ /* write the message to the socket connection */ int n = write( sock, msg, strlen( msg ) ); if ( n < strlen( msg ) ) { perror( "write() failed" ); return EXIT_FAILURE; } } if ( FD_ISSET( sock, &readfds ) ) { char buffer[1024]; int n = read( sock, buffer, 1024 ); if ( n < 1 ) { perror( "read() failed" ); } else { buffer[n] = '\0'; printf( "Rcvd msg from server: %s", buffer ); } } } close( sock ); return EXIT_SUCCESS; }