客户端:
int my_read(int fd,void *buf,size_t len);
int my_write(int fd,void *buf,size_t len);
int pro_echo(int sockfd);
int set_fl(int fd,int flags,int on);
int main(int argc,char **argv)
{
int sockfd,ret;
struct sockaddr_in servaddr;
struct hostent *server;
char buffer[BUFFER_SIZE];
if(argc!=2)
{
fprintf(stderr,"Usage:%s <hostname>\n",argv[0]);
return RET_ERR;
}
server=gethostbyname(argv[1]);
if(server==NULL)
{
hstrerror(h_errno);
return RET_ERR;
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
perror("socket");
return RET_ERR;
}
ret=set_fl(sockfd,O_NONBLOCK,1);
if(ret<0)
{
goto failed;
}
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(ECHO_PORT);
//servaddr.sin_addr.s_addr=*((uint32_t *)(*(server->h_addr_list)));
servaddr.sin_addr.s_addr=*(uint32_t *)server->h_addr;
ret=connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
if(ret<0)
{
perror("connect");
goto failed;
}
while(1)
{
printf("Enter the message:");
if((fgets(buffer,sizeof(buffer)-1,stdin))==NULL)
{
break;
}
ret=my_write(sockfd,(void *)buffer,strlen(buffer));
if(ret<0)
{
perror("write");
break;
}
ret=my_read(sockfd,(void *)buffer,sizeof(buffer)-1);
if(ret<0)
{
perror("read");
break;
}
else if(ret==0)
{
printf("server disconnect");
break;
}
buffer[ret]=0;
printf("Server echo message:%s\n",buffer);
}
failed:
close(sockfd);
return (ret<0 ? RET_ERR : RET_OK);
}
int my_read(int fd,void *buf,size_t len)
{
int cc,total=0;
while(len>0)
{
cc=read(fd,(char *)buf,len);
if(cc<0)
{
if(errno==EINTR)
{
continue;
}
return cc;
}
if(cc==0)
{
break;
}
buf=((char *)buf)+cc;
total+=cc;
len-=cc;
}
return total;
}
int my_write(int fd,void *buf,size_t len)
{
int cc,total=0;
while(len>0)
{
cc=write(fd,(const char *)buf,len);
if(cc<0)
{
if(errno==EINTR);
{
continue;
}
return cc;
}
buf=((char *)buf)+cc;
total+=cc;
len=len-cc;
}
return total;
}
int set_fl(int fd,int flags,int on)
{
int fl;
if((fl=fcntl(fd,F_GETFL,0))==-1)
{
perror("fcntl get");
return -1;
}
if(on)
{
fl|=flags;
}
else
{
fl&=~flags;
}
if((fl=fcntl(fd,F_SETFL,fl))==-1)
{
perror("fcntl set");
return -1;
}
return 1;
}
杨__羊羊