我有以下基本的 C++ 代码,用于使用 linux 上的套接字通过 UDP 传输文件。问题是,并不是所有的数据包都被传递(比如只收到 345kb 中的 8 个字节),我知道 UDP 不可靠,但这与我的代码有关还是仅仅因为 UDP 的不可靠性?
客户端
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=inet_addr("192.168.0.152");
servaddr.sin_port=htons(32000);
ifstream myfile("345kb.doc", ios::in);
int i=0;
char* memblock;
double size;
if(myfile.is_open()) {
myfile.seekg(0,ios::end);
size=(double)myfile.tellg();
memblock=new char[1024];
myfile.seekg(0,ios::beg);
double filesize=size;
cout<<filesize;
int n;
int ab=(int)filesize%1024;
while(filesize>1024){
myfile.read(memblock,1024);
cout<<"\nREAD:"<<strlen(memblock)<<"\n"<<"SENT:";
n=sendto(sockfd,memblock,strlen(memblock),0,(struct sockaddr *)&servaddr,sizeof(servaddr));
filesize=filesize-1024;
cout<<n<<"\n";
}
myfile.read(memblock,1024);
n=sendto(sockfd,memblock,strlen(memblock),0,(struct sockaddr *)&servaddr,sizeof(servaddr));
std::cout<<"HI"<<endl;
} else {
printf("\nFILE NOT OPENED \n");
}
服务器端
int sockfd,n;
struct sockaddr_in servaddr,cliaddr;
socklen_t len;
char mesg[1024];
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(32000);
bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
//for (;;)
//{
ofstream myfile;
myfile.open("345kbsssss.doc",ios::out|ios::app);
if(myfile.is_open()) {
long i=0;
len = sizeof(cliaddr);
while((n = recvfrom(sockfd,mesg,1024,0,(struct sockaddr *)&cliaddr,&len))>0){
std::cout<<"HI\n";
//n=recvfrom(sockfd,mesg,256,0,(struct sockaddr *)&cliaddr,&len);
myfile.write(mesg,n);
}
}
else printf("\nFILE NOT CREATED\n");
//}