#include #define SERVPORT 5555 //服务器监听窗口
#define BACKLOG 10 //请求队列的长度数
#define BUFFSIZE 1024
int main(int argc,char *argv[])
{
int ret = 0;
int flag = 0;
int socketfd = 0;
int filefd = 0;
struct sockaddr_in serv_addr; //客服端IP地址和端口信息
int addrlen = sizeof(serv_addr);
char buf[BUFFSIZE];
socketfd = socket(AF_INET,SOCK_STREAM,0);
if(socketfd == -1)
{
perror("socketfd:");
return -1;
}
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVPORT);
inet_aton("127.0.0.1",(struct sockaddr *)&serv_addr.sin_addr.s_addr);
flag = 0; //connect超时机制标志
do
{
ret = connect(socketfd,(struct sockaddr *)&serv_addr,addrlen);
if(ret == -1)
{
perror("connect:");
flag++;
}
if(flag > 3)
{
close(socketfd);
return -1;
}
sleep (1);
}while(ret < 0);
//transfer file
filefd = open(argv[1], O_RDONLY);
if (filefd < 0)
{
perror("open file:");
close(socketfd);
return -1;
}
do
{
memset(&buf,0,sizeof(buf));
ret = read(filefd, buf, BUFFSIZE);
if (ret < 0)
{
perror("read error:");
close(socketfd);
close(filefd);
return -1;
}
if (write(socketfd, buf, ret) < 0)
{
perror("write error");
close(socketfd);
close(filefd);
return -1;
}
}while(ret);
close(socketfd);
close(filefd);
return 0;
}