📄 xuchuan.c
字号:
//断点续传的小程序,实现文件传输中断后从断点开始传送#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h>#include <fcntl.h>#define PORT 2048 /* Server的端口 */ int main(int argc, char *argv[]) { int sockfd, numbytes, sin_size; struct hostent *he; /* 主机信息 */ struct sockaddr_in their_addr; /* 对方地址信息 */ if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } /* get the host info */ if ((he=gethostbyname(argv[1])) == NULL) { herror("gethostbyname"); exit(1); } if ((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1) { perror("socket"); exit(1); } their_addr.sin_family = AF_INET; their_addr.sin_port = htons(PORT); /* short, NBO */ their_addr.sin_addr = *((struct in_addr *)he->h_addr); bzero(&(their_addr.sin_zero), 8); /* 其余部分设成0 */ int i; for(i=0;i<2;i++) { numbytes = sendto(sockfd, "aaaaaaaaaaa", 11, 0, (struct sockaddr *)&their_addr,sizeof(their_addr)); printf("datagram from %s\n",inet_ntoa(their_addr.sin_addr)); } char buf[2048]; long offset; int fd; fd=open("test.mp3",O_RDWR|00666); if(fd==-1) { perror("open:"); exit(1); } while(1) { int readbytes,sendbytes; readbytes=read(fd,buf,2048); if(readbytes==-1) { perror("read:"); exit(1); } printf("readbytes==%d\n",readbytes); sendbytes=sendto(sockfd, buf, readbytes, 0, (struct sockaddr *)&their_addr,sizeof(their_addr)); printf("sendbytes==%d\n",sendbytes); printf("zhengzai fa song...\n"); if(getchar()=='a') { offset=lseek(fd,0,SEEK_CUR); printf("offset===%d\n",offset); close(fd); sleep(1); printf("close file\n"); break; } } printf("跳出第一个while\n"); int ff; ff=open("test.mp3",O_RDWR|00666); if(ff==-1) { perror("open:"); exit(1); } printf("offset===%d\n",offset); int a = lseek(ff,offset,SEEK_SET); if(a==-1) { perror("lseek:"); exit(1); } while(1) { int readbytes,sendbytes; //readbytes=fread(buf,1,2048,fb); readbytes=read(ff,buf,2048); printf("readbytes===%d\n",readbytes); sendbytes=sendto(sockfd, buf, readbytes, 0, (struct sockaddr *)&their_addr,sizeof(their_addr)); if(readbytes==0) { //if(feof(ff)) //{ //fclose(ff); close(ff); printf("file end ,close file\n"); break; //} } } close(sockfd); return 0; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -