/* Stream client, by Tom Sykora */ #include #include #include #include #include #include #include #include #include #include /*This program creates a socket and initiates a connection * *with the socket given in the command line. */ int main(int argc, char *argv[]) { int sock; int i=0; /* loop counter*/ char tick[3],tick1[3]; /*ticker symbol*/ struct sockaddr_in server; struct hostent *hp; char buf[1024]; char line[50]; char *tempstr; int rval; /*error code for read of data*/ /* Create socket */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("opening stream socket"); exit(1); } /* Connect socket using name specified by command line. */ server.sin_family = AF_INET; hp = gethostbyname(argv[1]); if (hp == 0) { fprintf(stderr, "%s: unknown host0", argv[1]); exit(2); } bcopy(hp->h_addr, &server.sin_addr, hp->h_length); server.sin_port = htons(atoi(argv[2])); if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) { perror("connecting stream socket"); exit(1); } /*request stock quote for a certain ticker symbol(1to5)*/ printf("Enter upto five ticker symbols separated by blanks\n"); gets(line); if (strlen(line)>2) { strcpy(tick,strtok(line," ")); if (write(sock, tick, sizeof(tick)) < 0) perror("writing on stream socket"); bzero(buf, sizeof(buf)); /*set buffer to zero*/ if ((rval = read(sock,buf,sizeof(buf))) < 0) /*accept data from server*/ perror("reading stream message"); if (rval == 0) /*no more data to receive*/ printf("Ending connection\n"); else /*print the data received*/ printf("\n%s\n", buf); while (((tempstr = strtok(NULL, " ")) != NULL) && i<=3) { strcpy(tick1,tempstr); if (write(sock, tick1, sizeof(tick1)) < 0) perror("writing on stream socket"); i++; /*increment loop counter to ensure no more than five symbols*/ bzero(buf, sizeof(buf)); /*set buffer to zero*/ if ((rval = read(sock,buf,sizeof(buf))) < 0) /*accept data from server*/ perror("reading stream message"); if (rval == 0) /*no more data to receive*/ printf("Ending connection\n"); else /*print the data received*/ printf("\n%s\n", buf); } } close(sock); /*close connection*/ return 0; }