python - 通过套接字传输大文件

标签 python c sockets winapi

我练习套接字编程,我写了一段代码(服务器:python,客户端:C/C++)通过套接字传输数据。使用小文件,它可以完美运行。然后我尝试使用更大的文件,它只传输该文件的一部分。这是我的代码:

服务器

def recv_file_from_client(conn):
    f = open("torecv","wb")
    while(True):
        l = conn.recv(1024)
        if "Done" in l:
            break
        f.write(l)
    f.close()
    print "Done recv"

客户端

BOOL SendFile(TCHAR* file) {
    FILE* filewrite = fopen("test.txt", "a");
    FILE* fp = _wfopen(file, L"rb");
    unsigned char buffer[1024] = { NULL };
    int readedChar;
    int total = 0;
    char log[128] = { NULL };
    while ((readedChar = fread(buffer, 1, 1024, fp)) > 0) {
        if (send(s, (const char*)buffer, sizeof(buffer), 0)) {
            total += readedChar;
            sprintf(log, "%d\n", total);
            fputs(log,filewrite);
        }
        memset(buffer, 0, 1024);
    }
    send(s, "Done", 1024, 0);
    fclose(fp);
    return TRUE;
}

Result

最佳答案

你的发送代码有很多逻辑错误:

  • 缺乏足够的错误处理。

  • 将错误的缓冲区大小传递给 send()(提示,如果文件大小不是 1024 的偶数倍,则最后一个缓冲区不会是 1024)。

  • 假设 send() 一次发送整个缓冲区(提示,它很少这样做)。您需要在循环中调用 send(),直到发送完整个缓冲区。

  • 误解了 send() 的返回值(提示,它不返回 bool 值)。它返回实际发送的字节数(好吧,在后台接受套接字内部缓冲区传输的字节数)。

  • 在每个 send() 之后将错误的值添加到 total,因为您假设 send() 中的整个缓冲区一口气。

  • 在文件末尾发送分隔符字符串,而不考虑此类分隔符是否出现在正在发送的文件中。在发送文件字节之前先发送文件大小会更安全。

  • 发送分隔符字符串时指定了错误的缓冲区大小(提示,“Done” 的大小不是 1024 字节)。

  • 泄漏 filewrite 句柄。您没有为它调用 fclose()

话虽如此,请尝试更像这样的方法:

BOOL SendRaw(const void *buffer, int size) {
    const char *ptr = (const char*)buffer;
    int numSent;
    while (size > 0) {
        numSent = send(s, ptr, size, 0);
        if (numSent == -1)
            return FALSE;
        ptr += numSent;
        size -= numSent;
    }
    return TRUE;
}

BOOL SendFile(const wchar_t* file) {
    FILE* filewrite = fopen("test.txt", "a");
    if (!filewrite)
        return FALSE;

    FILE* fp = _wfopen(file, L"rb");
    if (!fp) {
        fclose(filewrite);
        return FALSE;
    }

    if (fseek(fp, 0, SEEK_END) != 0) {
        fclose(fp);
        fclose(filewrite);
        return FALSE;
    }

    long size = ftell(fp);
    if (size == -1L) {
        fclose(fp);
        fclose(filewrite);
        return FALSE;
    }

    rewind(fp);

    uint32_t tmp = htonl(size);
    if (!SendRaw(&tmp, sizeof(tmp))) {
        fclose(fp);
        fclose(filewrite);
        return FALSE;
    }

    unsigned char buffer[1024];
    int numBytes, numSent, total = 0;

    while (size > 0) {
        numBytes = fread(buffer, 1, min(sizeof(buffer), size), fp);
        if (numBytes < 1) {
            fclose(fp);
            fclose(filewrite);
            return FALSE;
        }
        if (!SendRaw(buffer, numBytes)) {
            fclose(fp);
            fclose(filewrite);
            return FALSE;
        }
        size -= numBytes;
        total += numBytes;
        fprintf(filewrite, "%d\n", total);
    }

    fclose(fp);
    fclose(filewrite);
    return TRUE;
}
import struct

def recv_file_from_client(conn):
    f = open("torecv","wb")
    data = conn.recv(4)
    if not data:
        print "Error recv"
        return
    size = struct.unpack("!I", data)[0]
    while(size > 0):
        data = conn.recv(min(1024, size))
        if not data:
            print "Error recv"
            return
        f.write(data)
        size -= len(data)
    f.close()
    print "Done recv"

关于python - 通过套接字传输大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58620932/

相关文章:

python - PyQt4 到 PyQt5 怎么样?

c - 如何释放从 GdipCreateBitmapFromHBITMAP 创建的对象?

python - 使用 Anaconda python 代替默认的 mac python

python - 在 python 中使用插槽是个好主意吗?

c++ - 在 C++ 中传递命令行参数

将毫秒转换为 GNU 端口的时间规范

c - 为什么我们只能直接访问一个PCI物理地址中的640k-1MB区域?

c++ - 0MQ - 获取消息 ip

java - Android检查远程服务器是否在线

javascript - 在 Chrome 应用程序中无法取消暂停 TCP 服务器的 TCP 连接