简体   繁体   English

使用Winsock将文件分解成块,然后以二进制形式从客户端发送到C中的服务器吗?

[英]Break a file into chunks and send it as binary from client to server in C using winsock?

I created an application that send a text file from client to server So far i'm send it as string like this: 我创建了一个将文本文件从客户端发送到服务器的应用程序,到目前为止,我将其作为字符串发送,如下所示:

fp = fopen(filename, "r");
    if (fp != NULL) {
        newLen = fread(source, sizeof(char), 5000, fp);
            if (newLen == 0) {
                fputs("Error reading file", stderr);
            } else {
    source[++newLen] = '\0'; /* Just to be safe. */
            }
    }else{
        printf("The file %s does not exist :(");
        return 1;
    }


    fclose(fp);

    send(s , source , strlen(source) , 0); //send file

However my professor told me I must send the file in Binary and be ready to accept a file of any size I'm trying to figure out how to send the file in binary and break it into chunks 但是我的教授告诉我,我必须以二进制格式发送文件,并准备接受任何大小的文件,我试图弄清楚如何以二进制格式发送文件并将其分成大块

You can copy it one byte at a time. 您可以一次复制一个字节。

Reading/writing more than a byte at a time theoretically would make it read and write more efficiently to disk. 理论上说 ,一次读取/写入一个字节以上将使它对磁盘的读取和写入效率更高。 But since the binary is likely short, and disk I/O is already internally buffered it probably doesn't make a noticeable difference. 但是由于二进制文件可能很短,并且磁盘I / O已经在内部进行了缓冲,因此可能不会产生明显的变化。

perror() is a convenient function that displays the text associated with an error code returned from the most recent UNIX system call. perror()是一个方便的函数,用于显示与从最近的UNIX系统调用返回的错误代码关联的文本。 The text in the quotes is the title it displays before showing you the system message associated with the code. 引号中的文本是在显示与代码关联的系统消息之前显示的标题。

exit(EXIT_FAILURE) exits with a -1 value which is what scripts can test to see if your program succeeded or failed, as the exit status can be retrieved for a UNIX program. exit(EXIT_FAILURE)以-1值退出,这是脚本可以测试以查看您的程序成功还是失败的方法,因为可以为UNIX程序检索退出状态。

size_t is an integer type, but it's named size_t to give a hint as to what you're using it for. size_t是整数类型,但是它被命名为size_t来提示您使用它的目的。

If you wanted to transfer more data at a time you could. 如果您想一次传输更多数据,则可以。 But 1-byte xfers is simple and safe and it works. 但是1字节xfers简单安全,并且可以正常工作。

FILE *exein, *exeout;

exein = fopen("filein.exe", "rb");
if (exein == NULL) {
    /* handle error */
    perror("file open for reading");
    exit(EXIT_FAILURE);
}
exeout = fopen("fileout.exe", "wb");
if (exeout == NULL) {
    /* handle error */
    perror("file open for writing");
    exit(EXIT_FAILURE);
}
size_t n, m;
unsigned char buff[8192];
do {
    n = fread(buff, 1, sizeof buff, exein);
    if (n) 
        m = fwrite(buff, 1, n, exeout);
    else   
        m = 0;
} while ((n > 0) && (n == m));
if (m) 
   perror("copy");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM