注意:函数从客户端接收服务器上的“data”
客户端代码
void send_file(FILE *fp, int sockfd){
int size;
char *buffer;
while ((fp = fopen("/home/regs_p/cprograms/crypt/RSA.c","r")) != NULL){
if (fp == NULL) {
printf("Error opening the file : RSA.c\n");
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
rewind (fp);
// Allocate a buffer to contain all characters of the file
buffer = calloc(1, sizeof (char) * (size + 1));
if (buffer == NULL){
fprintf(stderr, "Sorry, space is insufficient!");
exit(EXIT_FAILURE);
}
fread(buffer, size, 1, fp);
printf("File size = %d\n", size);
write(sockfd, buffer, strlen(buffer));
free(buffer);
fclose(fp);
}
close(sockfd);
return;
} 服务器代码
void recv_file(int sockfd){
char *buffer;
buffer = calloc(1, sizeof (char) * (strlen(sockfd));
if (buffer == NULL) {
fprintf(stderr, "Sorry, but you can not insert more articles, the space is insufficient\n");
exit (EXIT_FAILURE);
}
printf("Length of the file received has %d characters!", strlen(buffer));

发布于 2020-08-18 15:26:05
有三件事:
strlen希望它的参数具有char *类型,并且是指向以零结尾的字符串的第一个字符的指针。sockfd不是这两样东西。将其从int转换为指针类型不会修复任何问题,因为它不是指针值。strlen返回一个size_t类型的值,而不是int类型,因此您需要使用%zu转换说明符而不是%d来打印它。错误缓冲区的长度需要由套接字文件描述符以外的其他内容来确定。您需要向recv_file函数传递第二个参数:
void recv_file( int sockfd, size_t bufsize )
{
char *buffer = calloc( bufsize+1, sizeof *buffer );
if ( !buffer )
...
}或者你需要依赖一个常量:
#define BUFFER_SIZE 128 // or however long it needs to be
...
void recv_file( int sockfd )
{
char *buffer = calloc( BUFFER_SIZE+1, sizeof *buffer );
if ( !buffer )
...
}此时,您最好让buffer成为一个常规数组:
void recv_file( int sockfd )
{
char buffer[BUFFER_SIZE+1] = {0};
...
}并且完全避免内存管理方面的麻烦。
发布于 2020-08-18 20:56:18
而且,您不能通过查看tcp连接来判断文件的长度。您必须先发送长度,然后再发送数据。你需要继续在接收上循环。
这是因为tcp是流协议。唯一的保证是,你们发出的再见是以同样的顺序到达的。但是,您可以执行1次发送50字节并接收50字节消息。
https://stackoverflow.com/questions/63471439
复制相似问题