/*
* echoclt_v3.c */
#include "echoclt.h"
#include "util.h"
void str_clt(FILE *fp, int sockfd);
int
main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in svraddr;
int i;
if(argc != 2){
fprintf(stderr, "usage: %s \n", argv[0]);
exit(1);
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket()");
exit(1);
}
bzero(&svraddr, sizeof(svraddr));
svraddr.sin_family = AF_INET;
svraddr.sin_port = htons(SVR_PORT);
inet_pton(AF_INET, argv[1], &svraddr.sin_addr);
if(connect(sockfd,
(struct sockaddr *)&svraddr,
sizeof(svraddr)) < 0){
perror("connect()");
exit(1);
}
str_clt(stdin, sockfd);
exit(0);
}
void
str_clt_old(FILE *fp, int sockfd)
{
char sendline[MAXLINE], rcvline[MAXLINE];
while(fgets(sendline, MAXLINE, fp) != NULL){
writen(sockfd, sendline, strlen(sendline));
if(readline(sockfd, rcvline, MAXLINE) == 0){
perror("readline()");
exit(1);
}
fputs(rcvline, stdout);
}
}
void
str_clt(FILE *fp, int sockfd)
{
int maxfd;
fd_set rset;
char sendline[MAXLINE], rcvline[MAXLINE];
FD_ZERO(&rset);
for( ; ; ){
FD_SET(fileno(fp), &rset); /* set two fd */
FD_SET(sockfd, &rset);
maxfd = max(fileno(fp), sockfd) + 1;
if(select(maxfd, &rset, NULL, NULL, NULL) < 0){
fprintf(stderr, "select(): %s\n", strerror(errno));
return;
}
if(FD_ISSET(sockfd, &rset)){ /* socket is readable */
if(readline(sockfd, rcvline, MAXLINE) == 0) {
fprintf(stderr, " server terminated prematurely\n");
return ;
}
fputs(rcvline, stdout);
}
if(FD_ISSET(fileno(fp), &rset)){ /* input is readable */
if(fgets(sendline, MAXLINE, fp) == NULL)
return;
writen(sockfd, sendline, strlen(sendline));
}
}
}
|