使用socket下載檔案(C++)
阿新 • • 發佈:2019-01-02
剛學習socket程式設計,寫了一個下載檔案的小程式,寫的不好大家不要吐槽。
客戶端:
#include<stdio.h> #include<stdlib.h> #include<arpa/inet.h> #include<sys/types.h> #include<sys/socket.h> #include<string.h> #include<unistd.h> #define BUFF_SIZE 100 int main(int argv,char *args[]){ int servsock; struct sockaddr_in servaddr; if(argv!=3){ printf("Usage:%s <ip><port>",args[0]); exit(1); } servsock = socket(PF_INET,SOCK_STREAM,0); if(servsock == -1) { printf("socket() error\n"); exit(1); } memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(args[1]); servaddr.sin_port = htons(atoi(args[2])); if(connect(servsock,(struct sockaddr*)&servaddr,sizeof(servaddr)) ==-1) { printf("connect() error\n"); exit(1); }else{ printf("connected.....\n"); } printf("please input filename:"); char filename[BUFF_SIZE]; memset(filename,0,sizeof(char)*BUFF_SIZE); scanf("%s",filename); write(servsock,filename,strlen(filename)); int successFlag; read(servsock,&successFlag,sizeof(successFlag)); if(successFlag!=1){ printf("input file is not existed!\n successFlag is %d\n",successFlag); exit(1); }else{ FILE *fp = fopen(filename,"w"); while(1){ memset(filename,0,BUFF_SIZE); int revlen = read(servsock,filename,BUFF_SIZE); if(revlen ==0) break; fputs(filename,fp); } fclose(fp); printf("complete!\n"); } close(servsock); return 0; }
伺服器:
#include<stdio.h> #include<stdlib.h> #include<arpa/inet.h> #include<sys/types.h> #include<sys/socket.h> #include<string.h> #include<unistd.h> #define BUFF_SIZE 100 int main(int argv,char *args[]){ int servsock,clntsock; struct sockaddr_in servaddr,clntaddr; if(argv!=2){ printf("Usage:%s <port>",args[0]); exit(1); } servsock = socket(PF_INET,SOCK_STREAM,0); memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(atoi(args[1])); if(bind(servsock,(struct sockaddr*)&servaddr,sizeof(servaddr)) ==-1) { printf("bind() error\n"); exit(1); } if(listen(servsock,5) ==-1) { printf("listen() error\n"); exit(1); } socklen_t len = sizeof(clntaddr); clntsock = accept(servsock,(struct sockaddr*)&clntaddr,&len); char filename[BUFF_SIZE]; int msglen=read(clntsock,filename,BUFF_SIZE); filename[msglen]=0; printf("receiver filename is: %s\n",filename); FILE *fp = fopen(filename,"r"); int successFlag = 0; if(fp) successFlag = 1; write(clntsock,&successFlag,sizeof(successFlag)); if(fp == NULL){ printf("NULL\n"); close(clntsock); close(servsock); return 0; } while(fgets(filename,BUFF_SIZE,fp)!=NULL){ int ll = strlen(filename); printf("length:%d content:%s",ll,filename); write(clntsock,filename,strlen(filename)); } fclose(fp); close(clntsock); close(servsock); return 0; }