gpt4 book ai didi

c - 使用read和write做服务器和客户端(FTP协议(protocol))

转载 作者:行者123 更新时间:2023-11-30 17:17:55 25 4
gpt4 key购买 nike

我的代码太长,无法在此处全部发布,因此我将总结一下问题所在。

在服务器部分,我在套接字上发送 3 件事:

  • 一条消息

  • 文件的内容

  • 另一条消息

在客户端部分我收到这些东西但是:

  • 这首先是在终端上打印

  • 第二个写入新文件

  • 最后在终端上打印

但是我的客户被困在阅读中,我真的不知道为什么。我花了一个小时来解决这个问题,所以如果有人可以帮助我,那就太好了!

编辑:基本上,我认为我的问题是我不知道要在服务器上什么来停止客户端上的读取。是\n\0..?

这是代码的第二部分:

服务器

void    send_content(t_server *s, FILE *fd, int rfd)
{
int len;
char *buff;

write(s->socket, "150 File status okay;" \
"about to open data connection.\n\0", strlen("150 File status okay;about to open data connection.\n\0"));
fseek(fd, 0, SEEK_END);
len = ftell(fd);
buff = malloc(len * sizeof(char));
read(rfd, buff, len);
write(s->socket, buff, len);
write(s->socket, "\n\0", strlen("\n\0"));
write(s->socket, "226 Closing data connection.\n\0", strlen("226 Closing data connection.\n\0"));
free(buff);
}

客户端

void    getfile(t_client *c, char **tab)
{
int ret;
int fd;
int z;
char buff[4096];

z = 0;
read(c->fd, buff, 4096);
write(1, buff, strlen(buff));
if (strlen(buff) < 25)
return ;
fd = creat(tab[1], S_IRUSR | S_IWUSR);
while (z == 0 && (ret = read(c->fd, buff, 4096)) > 0)
{
if (ret < 4096)
z = -1;
write(fd, buff, strlen(buff));
memset(buff, '\0', 4096);
}
read(c->fd, buff, 4096); // Stuck here
write(1, buff, strlen(buff));
close(fd);
}

最佳答案

如前所述,您需要一个读取函数,例如 this确保您收到指定的字节数(该函数将循环直到收到指定的字节数)。只需使用此 receivall 方法即可,而不必到处读取。对于文件,您通常首先发送文件长度,然后接收文件。我之前做过类似的事情,希望对你有一点帮助。这是客户端,它尝试从服务器接收第一个文件长度,然后是文件:

        /* create file */
FILE * ptrMyFile = fopen(&filenames[i][0],"wb");
if(NULL == ptrMyFile)
{
printf("Unable to open file \n");
return 1;
}

int size = 0;
int t = 4;

/* first receive file size from server */
/* NOTE: error checking is omitted from code, nevertheless users should stil do some error checking when using this code */
readall(sockfd, (unsigned char*) &size, &t);

/* how many 256 byte chunks are there? */
int div = size / 256;

/* loop to receive each chunk. */
for(int k = 0; k < div; k++)
{
int chunk_size = 256;

/* make sure we receive 256 bytes */
readall(sockfd, buffer, &chunk_size);

/* write to file */
fwrite(buffer, chunk_size, 1, ptrMyFile);
}

/* read the final chunk. */
int whatsleft = size - 256 * div;
readall(sockfd, buffer, &whatsleft);

/* write */
fwrite(buffer, whatsleft, 1, ptrMyFile);

/* close file */
fclose(ptrMyFile);

我把服务器部分留给你了。

关于c - 使用read和write做服务器和客户端(FTP协议(protocol)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com