/* ** client */ #include #include #include #include #include #include #include #include #include #define PORT 3456 // the port client will be connecting to #define MAXDATASIZE 100 // max number of bytes we can get at once #define STDIN 0 int main(int argc, char *argv[]) { int sockfd, numbytes, c, cnt, sendbytes, loop; char buf[MAXDATASIZE]; struct hostent *he; struct sockaddr_in their_addr; // connector's address information fd_set main, temp; if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } if ((he=gethostbyname(argv[1])) == NULL) { // get the host info herror("gethostbyname"); exit(1); } if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(PORT); // short, network byte order their_addr.sin_addr = *((struct in_addr *)he->h_addr); memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero); if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof their_addr) == -1) { perror("connect"); exit(1); } FD_ZERO(&main); FD_ZERO(&temp); FD_SET(sockfd, &main); FD_SET(STDIN, &main); cnt = 0; sendbytes = 0; loop = 1; while(loop) { temp = main; if(select(sockfd + 1, &temp, NULL, NULL, 0) == -1) { perror("select"); loop = 0; } if(FD_ISSET(sockfd,&temp)) { if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); loop = 0; } else if (numbytes > 0) { buf[numbytes] = '\0'; printf(" > %s",buf); } } if(FD_ISSET(STDIN, &temp)) { fgets(buf,MAXDATASIZE-1,stdin); sendbytes = strlen(buf) + 1; //MAXDATASIZE; printf("\n"); if (sendbytes && send(sockfd, buf, sendbytes, 0) == -1) { perror("send"); loop = 0; } else { sendbytes = 0; } } } close(sockfd); return 0; }