我正在编写一个简单的程序来将文件从一个点传输到另一个点。应用程序应显示选项
1.列出文件
2.下载文件
3.上传文件
但是一旦我选择了选项 1,它就会列出目录的内容,我会一一发送文件名,但所有名称都显示在客户端的一行中。不明白为什么..
然后它被困在标记的循环内,一旦recv完成,它应该退出循环,并且它应该再次呈现操作选项。我不确定问题是什么。 这是我的代码..
服务器.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;
}
客户端.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;
}
}
关于c - 没有从开关盒中出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45503279/