// Run like this: simple_client address port // Results in argv ["./simple_client", "address", "port"] #include #include #include #include #include #include #include #include #include "math_lib.h" #include #include #define DEBUG 1 int skt; void* read_thread(void* param){ /* Receive code starts here */ char operator; for(;;){ struct server_message sm; if(sizeof(sm) != recv(skt, &sm, sizeof(sm), MSG_WAITALL)){ printf(RED("Receive Error\n")); perror("recv"); break; } operator = (sm.type == SERVER_ADD)? '+':'*'; printf(CYAN("Received Result:")" %lf %c %lf = %lf\n", sm.operand_1, operator, sm.operand_2, sm.result); /* End of result recving code */ } return 0; } int main(int argc, char ** argv){ if(argc < 3){ printf("Usage: %s hostname port\n", argv[0]); return 1; } struct sockaddr_in sad; sad.sin_port = htons(atoi(argv[2])); sad.sin_family = AF_INET; skt = socket(AF_INET, SOCK_STREAM, 0); // do a dns lookup struct hostent* entry = gethostbyname(argv[1]); if(!entry){ if(h_errno == HOST_NOT_FOUND){ printf("This is our own message that says the host wasn't found\n"); } herror("gethostbyname"); return 1; } struct in_addr **addr_list = (struct in_addr**)entry->h_addr_list; struct in_addr* c_addr = addr_list[0]; char* ip_string = inet_ntoa(*c_addr); sad.sin_addr = *c_addr; // copy the address we found into sad // Finally done with DNS! printf("Connecting to: %s\n", ip_string); if( connect(skt, (struct sockaddr*)&sad, sizeof(struct sockaddr_in)) ){ perror("connect"); return 1; } char message[64]; size_t actual_length = read(skt, message, 64); printf("Received message(%lu bytes): %s\n", actual_length, message); pthread_t thread_handle; pthread_create(&thread_handle, 0, read_thread, 0); for(;;){ /* Here's where we start on the writing to the server part */ struct client_message cm; char operator; printf(GREEN("Enter a math problem like this: number operand number \n>> ")); scanf("%lf %c %lf", &cm.operand_1, &operator, &cm.operand_2); if(operator == '+') cm.type = CLIENT_ADD; else if(operator == '*') cm.type = CLIENT_MULTIPLY; else { printf(RED("Unsupported Operand: %c\n"), operator); continue; } if(DEBUG) printf(YELLOW("cm.type = %d, cm.operand_1 = %lf, cm.operand_2 = %lf\n"), cm.type, cm.operand_1, cm.operand_2); if(sizeof(cm) != write(skt, &cm, sizeof(cm))){ printf(RED("Send Error\n")); perror("write"); break; } /* Writing to the server is done now */ } close(skt); return 0; }