功能需求:
将本地文件夹下的source文件通过TCP备份到远程服务器
运行环境
:
unbuntu
客户端代码:
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/socket.h>
6 #include <netinet/in.h>
7 #include <arpa/inet.h>
8
9 //tcp客户端
10 int main()
11 {
12 //1. 准备socket
13 FILE* FP=fopen("source","r");
14 int sockfd=socket(PF_INET,SOCK_STREAM,0);
15 if(sockfd==-1)perror(""),exit(-1);
16 //2. 准备地址
17 struct sockaddr_in addr;
18 addr.sin_family = PF_INET;
19 addr.sin_port = htons(8888);
20 inet_aton("127.0.0.1",&addr.sin_addr);
21 //3.连接
22 int res = connect(sockfd,(struct sockaddr*)&addr, sizeof(addr));
23 if(res==-1)perror("连接失败"),exit(-1);
24 printf("连接成功\n");
25 //4.通信,发送文件名
26 send(sockfd, "source", 12, 0);
27 char buf[1024] = {};
28 //5.循环读取文件的每一行并发送给服务端
29 int count=1;
30 while(fgets(buf,sizeof(buf),FP)){
30 while(fgets(buf,sizeof(buf),FP)){
31 printf("第%d行:%s",count,buf);
32 send(sockfd,buf,sizeof(buf),0);
33 count++;
34 }
35 send(sockfd,"finished",strlen("finished"),0);
36 memset(buf,0,sizeof(buf));
37 recv(sockfd, buf, sizeof(buf), 0);
38 printf("服务端应答:%s\n", buf);
39 //5.关闭
40 shutdown(sockfd,SHUT_RDWR);
41 close(sockfd);
42 }
服务端代码:
1 #include <stdio.h>
2 #include <time.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <string.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <arpa/inet.h>
10
11 //tcp服务端
12 int main()
13 {
14 //1. 准备socket
15 int sockfd=socket(PF_INET,SOCK_STREAM,0);
16 if(sockfd==-1)perror(""),exit(-1);
17 //2. 准备地址
18 struct sockaddr_in addr;
19 addr.sin_family = PF_INET;
20 addr.sin_port = htons(8888);
21 inet_aton("127.0.0.1",&addr.sin_addr);
22 //3.绑定
23 int res = bind(sockfd,(struct sockaddr*)&addr, sizeof(addr));
24 if(res==-1)perror("绑定失败"),exit(-1);
25 printf("绑定成功\n");
26 //4.侦听
27 res=listen(sockfd,100);
28 if(res == -1)perror("监听失败"),exit(-1);
29 printf("启动侦听\n");
30
31 struct sockaddr_in cliaddr;
32 socklen_t len = sizeof(cliaddr);
33 //5.接受连接
34 int fd=accept(sockfd,(struct sockaddr*)&cliaddr,&len);
35 //6.接受文件名
36 char buf[100]={};
37 recv(fd,buf,sizeof(buf),0);
38 char path[256]={};
39 sprintf(path,"bak/%s",buf);
40 int sfd=open(path,O_RDWR|O_CREAT|O_APPEND,00755);
41 if(sfd==-1)
42 printf("\n%m,\nline:%d\n",__LINE__),exit(-1);
43
44 //7.循环接受文件内容,接受到空字符时退出
45 while(1){
46 memset(buf,0,sizeof(buf));
47 if(recv(fd,buf,sizeof(buf),0)<=0)
48 perror("接收数据终止"),exit(-1);
49 else if(!strcmp(buf,"finished")){
50 break;
51 }
52 else{
53 write(sfd,buf,sizeof(buf));
54 }
55 }
56 printf("接收完毕\n");
57 memset(buf,0,sizeof(buf));
58 time_t cur;
59 time(&cur);
60 struct tm* cur_tm=localtime(&cur);
61 sprintf(buf,"接收成功,接收时间:%4d-%02d-%02d %02d:%02d:%02d",cur_tm->tm_year+1900,cur_tm->tm_mon+1,cur_tm->tm_mday,cur_tm->tm _hour,cur_tm->tm_min,cur_tm->tm_sec);
62 send(fd,buf,strlen(buf),0);
63 close(fd);
64 close(sockfd);
65 }
66
缺陷与不足:
不支持多个客户端同时操作,在下一个版再添加多进程处理。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)