我目前正在制作一个简单的客户端和服务器,但遇到了问题。系统的一部分是让客户端查询服务器上的本地文件。该文件的内容必须发送给客户端。我能够将文件中的所有文本发送给客户端,但似乎卡在客户端的读取循环中。下面是代码吐为客户端和服务器这是为了应对这样的:在客户端读取文件后,Unix客户端和服务器陷入无限循环
,读取循环读取文件
else if(strcmp(commandCopy, get) == 0)
{
char *ptr;
int total = 0;
char *arguments[1024];
char copy[2000];
char * temp;
int rc;
strcpy(copy, command);
ptr = strtok(copy," ");
while (ptr != NULL)
{
temp = (char *)malloc(sizeof(ptr));
temp = ptr;
arguments[total] = temp;
total++;
ptr = strtok (NULL, " ");
}
if(total == 4)
{
if (strcmp(arguments[2], "-f") == 0)
{
printf("1111111111111");
send(sockfd, command, sizeof(command), 0);
printf("sent %s\n", command);
memset(&command, '\0', sizeof(command));
cc = recv(sockfd, command, 2000, 0);
if (cc == 0)
{
exit(0);
}
}
else
{
printf("Here");
strcpy(command, "a");
send(sockfd, command, sizeof(command), 0);
printf("sent %s\n", command);
memset(&command, '\0', sizeof(command));
cc = recv(sockfd, command, 2000, 0);
}
}
else
{
send(sockfd, command, sizeof(command), 0);
printf("sent %s\n", command);
memset(&command, '\0', sizeof(command));
while ((rc = read(sockfd, command, 1000)) > 0)
{
printf("%s", command);
}
if (rc)
perror("read");
}
}
服务器代码客户端代码
char* getRequest(char buf[], int fd)
{
char * ptr;
char results[1000];
int total = 0;
char *arguments[1024];
char data[100];
FILE * pFile;
pFile = fopen("test.txt", "r");
ptr = strtok(buf," ");
while (ptr != NULL)
{
char * temp;
temp = (char *)malloc(sizeof(ptr));
temp = ptr;
arguments[total] = temp;
total++;
ptr = strtok (NULL, " ");
}
if(total < 2)
{
strcpy(results, "Invaild Arguments \n");
return results;
}
if(pFile != NULL)
{
while(fgets(results, sizeof(results), pFile) != NULL)
{
//fputs(mystring, fd);
write(fd,results,strlen(results));
}
}
else
{
printf("Invalid File or Address \n");
}
fclose(pFile);
return "End of File \0";
}
执行命令的服务器代码
else if(strcmp(command, "get") == 0)
{
int pid = fork();
if (pid ==-1)
{
printf("Failed To Fork...\n");
return-1;
}
if (pid !=0)
{
wait(NULL);
}
else
{
char* temp;
temp = getRequest(buf, newsockfd);
strcpy(buf, temp);
send(newsockfd, buf, sizeof(buf), 0);
exit(1);
}
}
为什么不通过首先发送文件的大小(二进制)来简化代码?那么你可以只做一个阅读或至少知道你应该期待什么。 –
为什么不'仪器'您的代码发出调试/跟踪信息,以便您可以确切地看到哪个块导致问题。那么应该很容易找出它为什么会发生。另外,如果你确定它是导致循环的“客户端读取”,确认通过从图片中删除服务器,通过注释套接字的东西,如果它完成了,那么这是关于你处理套接字,如果继续无限循环,那么你需要看看你如何阅读你的文件。祝你好运。 – shellter