不从开关案件
问题描述:
我正在写一个简单的程序来将文件从一个点传输到另一个。该应用程序应该出现的选项
1.列表中的文件
2.下载文件
3.上传文件
但是,一旦我选择了选项1.它列出目录的内容,我送一个文件名通过一个,但所有的名字都出现在客户端的一行中。不知道为什么..不从开关案件
然后它卡在标记循环内,一旦recv完成,它应该从循环中出来,它应该再次提供操作选项。我不确定问题是什么。 这里是我的代码..
server.c
while(1){
//receive chosen option to be performed
if((rdata = recv(clnt, &x, sizeof(int), 0)) > 0){
opt = ntohl(x);
switch(opt){ //switch option and operate
case 1 : //option 1- transfer contents of the directory
if((dr = opendir(".")) != NULL){
while((de = readdir(dr)) != NULL){ //open directory
sprintf(filename, "%s",de->d_name);
rdata = send(clnt, filename, strlen(filename), 0); //transfer filenames
}
}
break;
}
client.c
while(1){ //this loop should continue after performing one option
printf("1. List available files on the server\n");
printf("2. Download a file\n");
printf("3. Upload a file to the server\n");
scanf("%d", &opt); //enter desired option
x = htonl(opt); //convert to network byte order
if(send(sockfd, &x, sizeof(int), 0) < 0){ //send option
perror("client: send");
continue;
}
switch(opt){
case 1 :
/************************************************************************/
while((rdata = recv(sockfd, filename, sizeof(filename), 0)) > 0){
filename[rdata] = '\0';
printf("> %s\n", filename);
}
/***********************************************************************/
break;
}
}
答
至少据我所知,直到执行正确的操作(在这种情况下,1要循环,2或3)。如果是程序应该退出。
int loop = 1;
while(loop){
loop = 0;
printf("1. List available files on the server\n");
printf("2. Download a file\n");
printf("3. Upload a file to the server\n");
scanf("%d", &opt);
x = htonl(opt);
if(send(sockfd, &x, sizeof(int), 0) < 0){
perror("client: send");
continue;
}
switch(opt){
case 1 :
while((rdata = recv(sockfd, filename, sizeof(filename), 0)) > 0){
filename[rdata] = '\0';
printf("> %s\n", filename);
}
break;
default:
loop = 1;
break;
}
}
或者也许你想退出循环选择
int loop = 1;
while(loop){
printf("1. List available files on the server\n");
printf("2. Download a file\n");
printf("3. Upload a file to the server\n");
printf("4. Exir\n");
scanf("%d", &opt);
x = htonl(opt);
if(send(sockfd, &x, sizeof(int), 0) < 0){
perror("client: send");
continue;
}
switch(opt){
case 1 :
while((rdata = recv(sockfd, filename, sizeof(filename), 0)) > 0){
filename[rdata] = '\0';
printf("> %s\n", filename);
}
break;
case 4:
loop = 0;
break;
default:
break;
}
}
它不工作,直到。问题出在'while((rdata = recv(sockfd,filename,sizeof(filename),0))> 0)'line。当你使用'recv()'而没有循环时,它可以正常工作。我想它被卡在循环内 – surjit
请编辑您的答案或删除它..这不是确切的答案 –