我正在试图找出如何将服务器上的文件名列表仅发送到客户端一次。现在通过阅读这里的问题,我知道如何使用以下内容从目录中获取所有文件名:
if(d)
{
while((dir = readdir(d)) != NULL)
{
if(dir->d_type == DT_REG)
{
if (sendto(sock, dir->d_name, sizeof(dir->d_name), 0, (struct sockaddr *) &clientAddr, sizeof(clientAddr)) != sizeof(dir->d_name))
{
printf("sendto() sent a different number of bytes than expected");
}
}
}
closedir(d);
}
根据我的理解,这将只读取文件名并将其发送到客户端。但是,当我执行此代码时,我的客户端会一直收到相同的文件名,直到它因分段错误而崩溃。为了解决这个问题,我试过这个:
if(d)
{
while((dir = readdir(d)) != NULL)
{
if(dir->d_type == DT_REG)
{
if(strcmp(dir_last, dir->d_name) != 0 || strlen(dir_last) == 1)
{
if (sendto(sock, dir->d_name, sizeof(dir->d_name), 0, (struct sockaddr *) &clientAddr, sizeof(clientAddr)) != sizeof(dir->d_name))
{
printf("sendto() sent a different number of bytes than expected");
}
strcpy(dir_last, dir->d_name);
}
else
{
break;
}
}
}
closedir(d);
}
我的想法是:
如果设置dir_last
(发送的最后一个文件名)的大小为1
('\0'
)或等于上次发送的dir_name
,则会中断否则循环发送文件的名称。但是,它只是保持循环和循环。
我要发送的文件名是:
server.c
client.c
Makefile
从服务器接收信息的客户端代码:
#define ECHOMAX 255 /* Longest string to echo */
int sock; /* Socket descriptor */
struct sockaddr_in echoServAddr; /* Echo server address */
unsigned int fromSize; /* In-out of address size for recvfrom() */
char echoString[1]; /* String to send to server */
char echoBuffer[ECHOMAX+1]; /* Buffer for receiving echoed string */
int echoStringLen; /* Length of string to echo */
/* Recv a response */
fromSize = sizeof(fromAddr);
if ((respStringLen = recvfrom(sock, echoBuffer, ECHOMAX, 0,
(struct sockaddr *) &fromAddr, &fromSize)) != ECHOMAX)
printf("recvfrom() failed\n");
if (echoServAddr.sin_addr.s_addr != fromAddr.sin_addr.s_addr)
{
fprintf(stderr,"Error: received a packet from unknown source.\n");
exit(1);
}
//ECHOBUFFER VALUE IS NOW FILENAME FROM SERVER
/* null-terminate the received data */
printf("%i\n", respStringLen);
echoBuffer[respStringLen] = '\0';
printf("Received: %s\n", echoBuffer); /* Print the echoed arg */