/** * client.c: client program which talks to the stasher.c RAM file servers * and allows user to send commands for processing. * * author: Bon Adriel Aseniero * base code provided by TA, Ali Abedi */ #include #include #include #include #include #define MAX_BUFFER_SIZE 1048576 /** * Prints an error message and exits * char *msg a pointer to the char array containing the error message */ void error( char *msg ) { perror( msg ); exit( 0 ); } /** * Checks if the given command is valid or not * returns 1 if valid otherwise 0 */ int isValidCommand( char *cmd ) { int flag = 0; if ( strncmp( cmd, "LIST", 4 ) == 0 || strncmp( cmd, "DONE", 4 ) == 0 || strncmp( cmd, "EXIT", 4 ) == 0 || strncmp( cmd, "STASH", 5 ) == 0 || strncmp( cmd, "VIEW", 4 ) == 0 || strncmp( cmd, "REMOVE", 6 ) == 0 ) flag = 1; return flag; } int main( int argc, char *argv[] ) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; // checking hostname provided char buffer[MAX_BUFFER_SIZE]; if ( argc < 3 ) { fprintf( stderr, "usage %s hostname port\n", argv[0] ); exit( 0 ); } // some socket programming provided by TA portno = atoi( argv[2] ); sockfd = socket( AF_INET, SOCK_STREAM, 0 ); if ( sockfd < 0 ) error( "ERROR opening socket" ); server = gethostbyname( argv[1] ); if ( server == NULL ) { fprintf( stderr, "ERROR, no such host\n" ); exit( 0 ); } bzero( (char *) &serv_addr, sizeof( serv_addr ) ); serv_addr.sin_family = AF_INET; bcopy( (char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons( portno ); if ( connect( sockfd, &serv_addr, sizeof( serv_addr ) ) < 0 ) error( "ERROR connecting" ); // While loop ensuring the user can send as much commands as he/she // wants until he/she disconnects using the commands DONE or EXIT while( 1 ) { // Display prompt printf( "Please enter one of the following the commands:\n" ); printf( "\tSTASH \t[stores a file into the RAM server]\n" ); printf( "\tLIST\t\t\t[lists all files in the server]\n" ); printf( "\tVIEW \t[shows the contents of the specified file]\n" ); printf( "\tREMOVE \t[deletes the specified file from server]\n" ); printf( "\tDONE\t\t\t[closes session but keeps the server running]\n" ); printf( "\tEXIT\t\t\t[closes session and server]\n:" ); bzero( buffer, MAX_BUFFER_SIZE ); // set string buffer fgets( buffer, MAX_BUFFER_SIZE-1, stdin ); // from user input if ( isValidCommand( buffer ) ) { n = write( sockfd, buffer, strlen( buffer ) ); // send the command to the server if ( n < 0 ) error( "ERROR writing to socket" ); // If the user uses the EXIT or DONE command, then quit the while loop if ( strncmp( buffer, "EXIT", 4 ) == 0 || strncmp( buffer, "DONE", 4 ) == 0 ) break; bzero( buffer, MAX_BUFFER_SIZE ); // clear buffer n = read( sockfd, buffer, MAX_BUFFER_SIZE-1 ); // read server response if ( n < 0 ) error( "ERROR reading from socket" ); printf( "%s\n", buffer ); // display server response } else printf( "Invalid Command: %s\n", buffer ); } return 0; }