这是客户端:
int main(int argc, char* argv[]){
int port;
int nrb;
int flag;
int file;
struct hostent *host;
unsigned int len;
char fileName[50];
int sock;
char* buffer;
int bytesRead;
char dest[50];
struct sockaddr_in sv_addr;
sscanf(argv[1], "%d", &port);
sscanf(argv[2], "%d", &nrb);
host=gethostbyname("127.0.0.1");
printf("%d%d", port, nrb);
buffer= (char*)malloc(nrb*sizeof(char));
sock= socket(AF_INET,SOCK_DGRAM, 0);
memset( &sv_addr,0,sizeof(struct sockaddr_in));
sv_addr.sin_family = AF_INET;
sv_addr.sin_port = htons(port);
sv_addr.sin_addr= *(struct in_addr*)host->h_addr_list[0];
len= sizeof(sv_addr);
printf("File name: ");
scanf("%s", fileName);
sendto(sock, fileName, sizeof(fileName), 0 , (struct sockaddr*)&sv_addr, len);
printf("before recvrom");
recvfrom(sock, &flag, sizeof(int), 0, (struct sockaddr*)&sv_addr,&len);
flag= htons(flag);
printf("recvfrom1: %d", flag);
if(flag==-1){
printf("The file does not exist.");
exit(0);
}
strcpy(dest,"./received/");
strcat(dest, fileName);
file=open(dest, O_WRONLY| O_CREAT | O_TRUNC, 0755);
do{
bytesRead= recvfrom(sock, buffer, nrb, 0, (struct sockaddr*)&sv_addr, &len);
write(file, buffer, bytesRead);
}while(bytesRead>0);
free(buffer);
close(file);
close(sock);
return 0;
}
它在调用之后被阻塞sendto
,因此它不会打印“在 recvfrom 之前”,但服务器会接收客户端发送的内容,并完成所有工作。这是服务器:
int main(int argc, char* argv[]){
int port;
unsigned int len;
int nrb;
char fileName[50];
struct sockaddr_in cl_addr;
sscanf(argv[1], "%d", &port);
sscanf(argv[2], "%d", &nrb);
sock=socket(AF_INET, SOCK_DGRAM, 0);
memset(&sock_addr, 0, sizeof(sock_addr));\
sock_addr.sin_family= AF_INET;
sock_addr.sin_port= htons(port);
sock_addr.sin_addr.s_addr=INADDR_ANY;
bind(sock, (struct sockaddr*)&sock_addr, sizeof(sock_addr));
len=sizeof(sock_addr);
recvfrom(sock, fileName, 256, 0, (struct sockaddr*)&cl_addr,&len);
printf("recieved: %s\n", fileName);
int readBytes,file, flag;
char* buffer;
flag=0;
file= open(fileName, O_RDONLY);
flag=htonl(file);
if(sendto(sock, &flag, sizeof(int), 0, (struct sockaddr*)&cl_addr,len )<0){
perror("sendto");
}
if(file== -1){
exit(0);
}
buffer=(char*)malloc(sizeof(char)*nrb);
do{
memset(buffer, 0, nrb);
readBytes= read(file, buffer, nrb);
printf("%s", buffer);
sendto(sock, buffer, nrb,0, (struct sockaddr*)&cl_addr, len);
}while(readBytes>0);
close(file);
free(buffer);
return 0;
}