gpt4 book ai didi

c - 正确传输客户端-服务器套接字连接中的文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:46 25 4
gpt4 key购买 nike

我编写了以下用于从客户端发送文件的代码:

FILE *fp = fopen("video.mp4","rb");
if(fp==NULL)
{
printf("File opern error");
return 1;
}

int bytesToWrite=84440670;
int bytesWritten=0;
while(bytesWritten<bytesToWrite)
{
int m=minimum(256,bytesToWrite-bytesWritten);
/* First read file in chunks of 256 bytes or the remaining bytes*/
unsigned char *buff=malloc(sizeof(char)*m);
bzero(buff, m);
int nread = fread(buff,1,m,fp);
printf("Bytes read %d \n", nread);
bytesWritten+=m;

/* If read was success, send data. */
if(nread > 0)
{
printf("Sending \n");
write(sockfd, buff, nread);
}

/*
* There is something tricky going on with read ..
* Either there was error, or we reached end of file.
*/
if (nread < 256)
{
if (feof(fp))
printf("End of file\n");
if (ferror(fp))
printf("Error reading\n");
break;
}


}

服务器端接收代码如下:

FILE *fp;
fp = fopen("receive.mp4", "wb");
if(NULL == fp)
{
printf("Error opening file");
return 1;
}
int bytesToRead=84440670;
/* Receive data in chunks of 256 or remaining bytes */
int totalbytesread=0;
while(totalbytesread < bytesToRead)
{
int m = minimum(256,bytesToRead-totalbytesread);
char *recvBuff=malloc(sizeof(char)*m);
bzero(recvBuff,m);
bytesReceived = read(newsocfd, recvBuff,m );
printf("Bytes received %d\n",bytesReceived);
totalbytesread += bytesReceived;
fwrite(recvBuff, 1,bytesReceived,fp);
}

if(bytesReceived < 0)
{
printf("\n Read Error \n");
}

.txt 文件的发送工作正常,在发送其他格式时一些数据丢失(例如,.mp4 文件的某些结束秒未发送)。我是套接字编程的新手。任何帮助将不胜感激。

最佳答案

您在完成接收后在服务器中缺少一个fclose(fp);。您还可以使用 fflush(fp); 来刷新内容。

此外,还有一些内存泄漏和错误处理不当的问题。

关于c - 正确传输客户端-服务器套接字连接中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28738179/

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